【问题标题】:Computes the average word length for all the words in a file?计算文件中所有单词的平均单词长度?
【发布时间】:2013-12-06 22:40:17
【问题描述】:

所以我需要编写一个程序来计算文件中所有单词的平均单词长度。到目前为止,我有这个并且完全迷失了

newfile=input('Enter file name: ')
f=open(newfile,'r')
count1=0
count2=0
for line in f:
    count1+=1
    words=line.rstrip().split()
for word in words:
    count2+=1
average=count1/count2
print('Average words per line: ',average)

【问题讨论】:

  • 我可能错了,但看起来您在这里所做的是在输入文件中创建字数与行数的比率。您是想要这样做,还是想要平均字长?
  • 您需要的唯一两件事是单词长度和单词数的总和。不要想太多。
  • 1.获取所有单词的总长度 2. 获取单词总数 3. 1/2 -> 会给你结果
  • totalWords = sum(1 for word in line.split() if word.isalpha())
  • 最好使用有助于理解代码的变量名。而不是count1 和count2,我建议num_words 和len_words(“文件中的单词数”和“文件中所有单词的总长度”的简短、易于键入的缩写) .对于简单的算术平均值(最常见的平均值),您将计算 len_words/num_words。在 Python 2.x 中,您应该首先明确地将其中至少一个强制为 float:float(len_words)/num_words,但在 Python 3.x 中,这不是必需的。

标签: python file average


【解决方案1】:

wi = 单词 i 的长度

wavg = ∑ wi / N

with open(input('Enter file name: '),'r') as f:
    w = [len(word) for line in f for word in line.rstrip().split(" ")]
    w_avg = sum(w)/len(w)

【讨论】:

  • 一项改进:w_avg = float(sum(w))/float(len(w))
  • 很好的解决方案 bcorso,以及很好的补充 @VladimirStazhilov。我还将更改 line1 以包含编码语句。 with open(input('Enter file name: '),'r', encoding="utf-8") as f: 非常轻微 - 干得好。
【解决方案2】:

问题是你从来没有真正计算过单词的长度。 你可以做的是嵌套你的 for 循环:

for line in f:
     for word in line.split():

然后递增计数器

       count1+=1
       count2+=len(word)   # len(word) gives you the length exactly

最后,确保在计算平均值时进行浮点除法(而不是整数除法):

average=float(count2)/float(count1)

我复制并解释你的原始代码,让你明白哪里出了问题:

newfile=input('Enter file name: ')
f=open(newfile,'r')
count1=0
count2=0
for line in f:                             # here, line is a string containing many words
    count1+=1                       
    words=line.rstrip().split()            # here, "words" is a LIST of words
                                           # you exit your for loop here
                                           # so far, you looped over all your lines and did nothing with them
                                           # and in your "words" variable, only the last line will be stored


for word in words:                         # here, "word" is a word
    count2+=1                              # you increment the counter with one, not with the word's length
average=count1/count2                      # here, you perform integer division, and will lose the real part of the result
print('Average words per line: ',average)

【讨论】:

    【解决方案3】:

    至于 Python 2.7:

    f = open('mercy.txt', 'r')
    
    w = [len(word) for line in f for word in line.rstrip().split(" ")]
    important to convert to float!
    w_avg = float(sum(w))/float(len(w))
    
    print 'Average word length: ', w_avg)
    f.close()
    

    【讨论】:

      猜你喜欢
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-01
      相关资源
      最近更新 更多