Python - 句子中单词长度的平均值

时间:2016-10-18 17:48:04

标签: python string

我有一个与此问题非常类似的问题:Python: How can I calculate the average word length in a sentence using the .split command?

我需要多个句子的平均单词长度。这就是我现在所拥有的。当我想要句子时,我得到了所有单词的平均值。也在第一行结尾处得到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)

3 个答案:

答案 0 :(得分:0)

让我们来看看这一行

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

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

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

希望你明白这个想法

答案 1 :(得分:-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]

答案 2 :(得分:-1)

试试这个:

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)