统计一个文本中单词频次最高的10个单词?

本文阅读 1 分钟
首页 Python笔记 正文
  1. import re
  2. # 方法一
  3. def test(filepath):
  4. distone = {}
  5. with open(filepath) as f:
  6. for line in f:
  7. line = re.sub("\W+", " ", line)
  8. lineone = line.split()
  9. for keyone in lineone:
  10. if not distone.get(keyone):
  11. distone[keyone] = 1
  12. else:
  13. distone[keyone] += 1
  14. num_ten = sorted(distone.items(), key=lambda x:x[1], reverse=True)[:10]
  15. num_ten =[x[0] for x in num_ten]
  16. return num_ten
  17. # 方法二
  18. # 使用 built-in 的 Counter 里面的 most_common
  19. import re
  20. from collections import Counter
  21. def test2(filepath):
  22. with open(filepath) as f:
  23. return list(map(lambda c: c[0], Counter(re.sub("\W+", " ", f.read()).split()).most_common(10)))
解压密码: detechn或detechn.com

免责声明

本站所有资源出自互联网收集整理,本站不参与制作,如果侵犯了您的合法权益,请联系本站我们会及时删除。

本站发布资源来源于互联网,可能存在水印或者引流等信息,请用户自行鉴别,做一个有主见和判断力的用户。

本站资源仅供研究、学习交流之用,若使用商业用途,请购买正版授权,否则产生的一切后果将由下载用户自行承担。

python代码实现删除一个list里面的重复元素
« 上一篇 01-31
请写出一个函数满足以下条件
下一篇 » 01-31

发表评论