如何计算文本文件中的平均句子长度(单词)包含使用python的100个句子

时间:2012-12-20 10:35:39

标签: python python-2.7 nlp

我有一个包含100个句子的文本文件。我想编写一个python脚本,它将计算包含100个句子的文本文件中的平均句子长度(以单词表示)。 感谢

3 个答案:

答案 0 :(得分:5)

天真的方式:

sents = text.split('.')
avg_len = sum(len(x.split()) for x in sents) / len(sents)

严肃的方法:使用nltk根据目标语言规则对文本进行标记。

答案 1 :(得分:3)

wordcounts = []
with open(filepath) as f:
    text = f.read()
    sentences = text.split('.')
    for sentence in sentences:
        words = sentence.split(' ')
        wordcounts.append(len(words))
average_wordcount = sum(wordcounts)/len(wordcounts)

答案 2 :(得分:0)

这应该可以帮到你。但这是基本的东西,你至少应该自己试一试。

此代码假定每个句子都在一个新行上。

如果不是这种情况,您可以更正代码,或在您的问题中反映出来,但目前还不清楚。

def read_lines_from_file(file_name):
    with open(file_name, 'r') as f:
        for line in f:
            yield line.strip()

def average_words(sentences):
    counts = []
    for sentence in sentences:
        counts.append(sentence.split())
    return float(sum(counts)/len(counts))

print average_words(read_lines_from_file(file_name))