python 统计list中所有str 中的单词长度 计算平均值
来源:学生作业帮 编辑:作业帮 分类:英语作业 时间:2024/05/18 13:03:07
python 统计list中所有str 中的单词长度 计算平均值
def avg_word_length(text):
""" (list of str) -> float
Precondition: text is non-empty. Each str in text ends with \n and
text contains at least one word.
Return the average length of all words in text.
>>> text = ['James Fennimore Cooper\n', 'Peter, Paul and Mary\n']
>>> avg_word_length(text)
5.142857142857143
"""
i = 0
n = 0
w = 0
for i in range(len(text)):
for word in text[i]:
for ch in word:
if ch != '':
n += 1
w += 1
return n / w
我的body是错的.return 1.0..求大神帮帮忙啊!
def avg_word_length(text):
""" (list of str) -> float
Precondition: text is non-empty. Each str in text ends with \n and
text contains at least one word.
Return the average length of all words in text.
>>> text = ['James Fennimore Cooper\n', 'Peter, Paul and Mary\n']
>>> avg_word_length(text)
5.142857142857143
"""
i = 0
n = 0
w = 0
for i in range(len(text)):
for word in text[i]:
for ch in word:
if ch != '':
n += 1
w += 1
return n / w
我的body是错的.return 1.0..求大神帮帮忙啊!
需要分词,用正则(re模块)会很方便,你确定你是初学者?因为不用正则的话,分词有点麻烦.里面是用逗号和空格分词的.
再问: 对啊,初学啊,刚刚学到dictionary 求帮助啊。。。
再答: text = ['James Fennimore Cooper\n', 'Peter, Paul and Mary\n']
import re
def avg_word_length(text):
word_count=0 #单词计数
all_word_len=0 #单词总长度
for line in text:
for word in re.split('\W+',line): #使用正则分词,\W+是非单词符号的意思
if word: #过滤空字符
all_word_len+=len(word)
word_count+=1
return all_word_len/float(word_count)
print(avg_word_length(text))
# 5.14285714286这是正则的。使用python2.7,精度不一样。
下面是一种凑合的方法,当然,没有用正则的通用性好。def avg_word_length(text):
word_count=0 #单词总数
all_word_len=0 #单词的字母总长度
last=' ' #存储上一个字符
for line in text:
for char in line:
if char in ' ,.\n':
if not(last in ' ,.\n'):
word_count+=1 #如果上一个字母不是分隔符,那么单词计数加1。为了处理连续的分隔符。
#这种计数的前提是结尾有一个换行符,不然会少计算一个单词数
else:
all_word_len+=1
last=char
return all_word_len/float(word_count)
再问: 对啊,初学啊,刚刚学到dictionary 求帮助啊。。。
再答: text = ['James Fennimore Cooper\n', 'Peter, Paul and Mary\n']
import re
def avg_word_length(text):
word_count=0 #单词计数
all_word_len=0 #单词总长度
for line in text:
for word in re.split('\W+',line): #使用正则分词,\W+是非单词符号的意思
if word: #过滤空字符
all_word_len+=len(word)
word_count+=1
return all_word_len/float(word_count)
print(avg_word_length(text))
# 5.14285714286这是正则的。使用python2.7,精度不一样。
下面是一种凑合的方法,当然,没有用正则的通用性好。def avg_word_length(text):
word_count=0 #单词总数
all_word_len=0 #单词的字母总长度
last=' ' #存储上一个字符
for line in text:
for char in line:
if char in ' ,.\n':
if not(last in ' ,.\n'):
word_count+=1 #如果上一个字母不是分隔符,那么单词计数加1。为了处理连续的分隔符。
#这种计数的前提是结尾有一个换行符,不然会少计算一个单词数
else:
all_word_len+=1
last=char
return all_word_len/float(word_count)
python 统计list中所有str 中的单词长度 计算平均值
python 统计单词平均长度,统计a出现的次数
用python统计list中只出现一次的单词的比例 (call了一个clean_up method 去掉了后面的\n)
python统计个单词数目
python如何统计列表的长度
python中如何统计两个字典中相同单词数量有多少个?
python 中如何将str(dict)后的字典还原?
python如何使两个不同list中的数相加
python 中,字典中的kay与list列表中的值比较,有相同的,则把相同的字典重新添加到新的字典中.
VF中的STR是什么意思 比如?str(1232.5678) 怎么计算呢
python将list存入字典
统计中,A±B,A是平均值,B是什么含义呢?如何计算?