鱼C论坛

 找回密码
 立即注册
查看: 3682|回复: 0

[技术交流] 文本词频统计

[复制链接]
发表于 2020-11-10 13:36:42 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
# 文本词频统计
# HamletV1:找一个哈姆雷特的文件,保存为hamlet.txt,放在同一目录里面
  1. def getText(filename):
  2.     txt = open(filename, "r").read()
  3.     txt = txt.lower()
  4.     for ch in '!@#$%^&*+-()[]{}<>=_:;\\‘’"|~.':
  5.         txt = txt.replace(ch, " ")
  6.     return txt

  7. f_name = "hamlet.txt"
  8. hamletTxt = getText(f_name)
  9. words = hamletTxt.split()
  10. counts = {}
  11. for word in words:
  12.     # word之前没有则创建初始值为0,然后逐次加1
  13.     counts[word] = counts.get(word, 0) + 1
  14. items = list(counts.items())
  15. items.sort(key=lambda x:x[1],reverse=True)
  16. # 将出现次数最多的前十个词输出
  17. for i in range(10):
  18.     word, count = items[i]
  19.     print("{0:<10}{1:>5}".format(word, count))
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-29 10:38

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表