2016-02-12 417 views
0

我需要编写一个函数来计算文件中的所有单词并打印单词的平均长度。 (标点符号务必被删除。)如何计算平均值?

def average(fileName): 
    infile = open(fileName,'r') 
    wordcount = {} 
     for word in infile.read().split(): 
     if word not in wordcount: 
     wordcount[word] = 1 
     else: 
     wordcount[word] += 1 

回答

0

如果你已经有了运行for循环后workcount阵列,你可以得到的单词数。 我想下一步是计算你的文本文件中的字母。

with open('text.txt') as counting: 
print Counter(letter for line in counting 
       for letter in line.lower() 
       if letter in ascii_lowercase) 

之后,你可以得到你想要的平均长度。

+0

我很努力得到一个字数与删除标点符号.... – ZigZag

0

如果我理解正确你:

import re 

non_word_chars = re.compile('\W+') 
nr_of_words = 0 
total_length = 0 
with open('test.txt') as f: 
    for word in f.read().split(" "): 
     word = non_word_chars.sub('', word) 
     nr_of_words += 1 
     total_length += len(word) 

print(round(total_length/nr_of_words)) 

时间和内存使用效率,因为它不涉及构建字典,并在其上重新运行计算平均值。