2016-02-12 403 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)) 

時間和內存使用效率,因爲它不涉及構建字典,並在其上重新運行計算平均值。