返回句子中单词长度的平均值



我有一个非常类似的问题:Python:我如何使用.split命令计算句子中的平均单词长度?

我需要多个句子的平均单词长度。这是我目前所拥有的。我得到的是所有单词的平均值,当我想要的是句子。在生成的第一行末尾也得到一个0。

words = "This is great. Just great."
words = words.split('.')
words = [sentence.split() for sentence in words]
words2 = [len(sentence) for sentence in words]
average = sum(len(word) for word in words)/len(words)
print(words2)
print(average)

让我们看看这一行

average = sum(len(word) for word in words)/len(words)

这里的len(words) = 2这不是单词的len。它是句子的len

average = sum(len(word) for word in words)/(len(words[0])+len(words[1]))

希望你能明白

sentences = words.split('.')
sentences = [sentence.split() for sentence in sentences if len(sentence)]
averages = [sum(len(word) for word in sentence)/len(sentence) for sentence in sentences]

试试这个:

data = "This is great. Just great."
sentences = data.split('.')[:-1]    #you need to account for the empty string as a result of the split
num_words = [len(sentence.split(' ')) for sentence in sentences]
average = sum(num for num in num_words)/(len(sentences))
print(num_words)
print(len(sentences))
print(average)

最新更新