File 如何计算平均值?

File 如何计算平均值?,file,file-io,python-3.4,word-count,python-3.5,File,File Io,Python 3.4,Word Count,Python 3.5,我需要编写一个函数,计算文件中的所有单词,并打印单词的平均长度。 (必须删除标点符号。) 如果在运行for循环后已经拥有workcount数组,则可以获得字数。 我认为下一步是计算文本文件中的字母 with open('text.txt') as counting: print Counter(letter for line in counting for letter in line.lower() if letter in asci

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


如果在运行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)

然后,您可以得到您想要的平均长度。

如果我理解正确:

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))
时间和内存效率都很高,因为它不需要构造一个dict并再次运行它来计算平均值

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))