【问题标题】:Get word count and average length from frequency dictionary从频率词典中获取字数和平均长度
【发布时间】:2013-12-07 17:23:27
【问题描述】:

如果我有一个频率词典,其中包含文本中的单词作为键,它们在文本中出现的次数作为值。如何通过确保考虑多次出现的单词来获得字数和平均长度?现在我所要做的就是制作一个键列表(因为它们是单词),然后使用 len() 来计算字数。

wordcount=len(list(freq.keys()))
report["count:"]=wordcount
#for average length:
avg=list(freq.keys())
average=sum(map(len,avg))/len(avg)
report["avglen"]=average

【问题讨论】:

  • len(freq) 足以计算字数。

标签: python dictionary python-3.3


【解决方案1】:

使用sum 函数和dict.values()

freq = { 'test' : 10, 'rep' : 100 }
wordcount = sum(freq.values())
average   = sum(len(w) * c for w, c in freq.items()) / wordcount
print(wordcount, average)

【讨论】:

    【解决方案2】:
    number_of_words  = int(raw_input("Enter the number of words. "))
    
    word_dict = {}
    
    for i in range(number_of_words):
        word = raw_input("Enter word. ")
        if word in word_dict:
            word_dict[word] += 1
        else:
            word_dict[word] = 1
    
    print word_dict
    
    print sum([len(word)*word_dict[word] for word in word_dict])/number_of_words
    

    一个非常相似的问题:https://stackoverflow.com/questions/20143947/word-frequency-counter-python/20145320#20145320

    【讨论】:

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