【问题标题】:Count the most frequently used words in a text file [duplicate]计算文本文件中最常用的单词[重复]
【发布时间】:2014-08-11 07:01:48
【问题描述】:

我这里有一个程序,它可以计算一个单词在我的 .txt 文件中使用的次数,并显示前 10 个最常用的单词。我希望在没有数字的情况下也显示这些信息,所以只是文字。任何帮助将不胜感激。

def countWordFrequency(Data1):
   myDict = {}
   fh = open(Data1, 'r')
   content = fh.read()
   listWords = content.split(" ")
   for w in listWords:
      if (myDict.has_key(w)):
         myDict[w] = myDict[w] + 1
      else:
         myDict[w] = 1
   fh.close()
   return myDict

freq = countWordFrequency('Data1.txt')
topfreq = sorted(freq.iteritems(), key=lambda x:-x[1])[:10]
for x in topfreq:
    print "{0}: {1}".format(*x)

【问题讨论】:

标签: python python-2.7 dictionary frequency word-count


【解决方案1】:

来点列表理解魔法怎么样?

f = open('Data1.txt','r')
words = [x for y in [l.split() for l in f.readlines()] for x in y]
print sorted([(w, words.count(w)) for w in set(words)], key = lambda x:x[1], reverse=True)[:10]

如果你足够努力,我相信你可以在一行中完成。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-25
    • 2013-12-09
    • 2017-04-24
    • 2016-01-23
    • 1970-01-01
    • 2013-05-05
    • 2015-07-13
    • 2022-12-12
    相关资源
    最近更新 更多