加载中...

菜谱 10:统计单词出现的频率


平时我们在工作的时候需要统计一篇文章或者网页出现频率最高的单词,或者需要统计单词出现频率排序。那么如何完成这个任务了?

例如,我们输入的语句是 “Hello there this is a test. Hello there this was a test, but now it is not.”,希望得到的升序的结果:

  1. [[1, 'but'], [1, 'it'], [1, 'not.'], [1, 'now'], [1, 'test,'], [1, 'test.'], [1, 'was'], [2, 'Hello'], [2, 'a'], [2, 'is'], [2, 'there'], [2, 'this']]

得到降序的结果是:

  1. [[2, 'this'], [2, 'there'], [2, 'is'], [2, 'a'], [2, 'Hello'], [1, 'was'], [1, 'test.'], [1, 'test,'], [1, 'now'], [1, 'not.'], [1, 'it'], [1, 'but']]

完成这个结果的代码如下:

  1. class Counter(object):
  2. def __init__(self):
  3. self.dict = {}
  4. def add(self, item):
  5. count = self.dict.setdefault(item, 0)
  6. self.dict[item] = count + 1
  7. def counts(self, desc=None):
  8. result = [[val, key] for (key, val) in self.dict.items()]
  9. result.sort()
  10. if desc:
  11. result.reverse()
  12. return result
  13. if __name__ == '__main__':
  14. '''Produces:
  15. >>> Ascending count:
  16. [[1, 'but'], [1, 'it'], [1, 'not.'], [1, 'now'], [1, 'test,'], [1, 'test.'], [1, 'was'], [2, 'Hello'], [2, 'a'], [2, 'is'], [2, 'there'], [2, 'this']]
  17. Descending count:
  18. [[2, 'this'], [2, 'there'], [2, 'is'], [2, 'a'], [2, 'Hello'], [1, 'was'], [1, 'test.'], [1, 'test,'], [1, 'now'], [1, 'not.'], [1, 'it'], [1, 'but']]
  19. '''
  20. sentence = "Hello there this is a test. Hello there this was a test, but now it is not."
  21. words = sentence.split()
  22. c = Counter()
  23. for word in words:
  24. c.add(word)
  25. print "Ascending count:"
  26. print c.counts()
  27. print "Descending count:"
  28. print c.counts(1)

还没有评论.