51学通信论坛2017新版

标题: 基本词频统计 [打印本页]

作者: admin    时间: 2019-6-23 12:57
标题: 基本词频统计
[attach]5797[/attach]

[attach]5798[/attach]

代码:
  1. # CalHamlet.py
  2. def getText():
  3.     txt = open("hamlet.txt", "r").read()
  4.     txt = txt.lower()
  5.     for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
  6.         txt = txt.replace(ch, " ")   #将文本中特殊字符替换为空格
  7.     return txt
  8. hamletTxt = getText()
  9. words  = hamletTxt.split()
  10. counts = {}
  11. for word in words:
  12.     counts[word] = counts.get(word,0) + 1
  13. items = list(counts.items())
  14. items.sort(key=lambda x:x[1], reverse=True)
  15. for i in range(10):
  16.     word, count = items[i]
  17.     print ("{0:<10}{1:>5}".format(word, count))
复制代码
结果:
  1. the        1138
  2. and         965
  3. to          754
  4. of          669
  5. you         550
  6. i           542
  7. a           542
  8. my          514
  9. hamlet      462
  10. in          436
复制代码





欢迎光临 51学通信论坛2017新版 (http://bbs.51xuetongxin.com/) Powered by Discuz! X3