Python作业4 文本词云统计,天生词云

打印 上一主题 下一主题

主题 1638|帖子 1638|积分 4916

编写程序,统计两会政府工作报告热词频率,并天生词云。
2025两会政府工作报告
  1. import jieba
  2. import wordcloud
  3. from collections import Counter
  4. import re
  5. # 读取文件
  6. with open("gov.txt", "r", encoding="gbk") as f:
  7.     t = f.read()
  8. # 分词处理
  9. ls = jieba.lcut(t)
  10. # 定义过滤函数
  11. def is_valid_word(word):
  12.     # 过滤条件:
  13.     # 1. 长度至少为2个字符(过滤单字)
  14.     # 2. 只包含中文(\u4e00-\u9fff)
  15.     # 3. 不是停用词(可选)
  16.     return (len(word) >= 2 and
  17.             all('\u4e00' <= char <= '\u9fff' for char in word))
  18. # 严格过滤
  19. filtered_words = [word for word in ls if is_valid_word(word)]
  20. # 统计词频
  21. word_counts = Counter(filtered_words)
  22. # 打印前20个高频词
  23. print("=== 纯中文热词统计 ===")
  24. for word, count in word_counts.most_common(20):
  25.     print(f"{word}: {count}次")
  26. # 生成词云
  27. txt = " ".join(filtered_words)
  28. w = wordcloud.WordCloud(
  29.     font_path="msyh.ttc",
  30.     width=1000,
  31.     height=700,
  32.     background_color="white",
  33.     max_words=200  # 限制词云显示的最大词数
  34. )
  35. w.generate(txt)
  36. w.to_file("wordcloud.png")
复制代码
  1. <img alt=""  src="https://i-blog.csdnimg.cn/direct/1e5c4767793a43e28396a1390b9a6648.png"  />
  2. <img alt=""  src="https://i-blog.csdnimg.cn/direct/ce0386d394d74bb693ac8a1b52d49acc.png"  />
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

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

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

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

本版积分规则

用多少眼泪才能让你相信

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表