Python实现政府工作报告文本分析:从词频统计到词云可视化全流程解析
基于Python的政府工作报告文本分析:从词频统计到词云生成
一、项目背景与目标
在政策研究和舆情分析领域,政府工作报告是解读国家发展战略的重要文本资料。本教程将展示如何运用Python对政府工作报告进行深度文本分析,通过词频统计和可视化呈现,快速抓住报告的核心关键词。
二、技术实现流程
1.文本获取:
从中国政府网下载最新《政府工作报告》文本,保存为government_report.txt
2.停用词表:
创建stopwords.txt,包含常见虚词和通用停用词,自行查找
1. 环境准备
import jieba
from wordcloud import WordCloud
from collections import Counter
import re
import matplotlib.pyplot as plt
2. 数据加载与清洗
# 读取报告文本(需准备government_report.txt)
with open("government_report.txt", "r", encoding="utf-8") as f:
text = f.read()
# 正则表达式去除非中文字符
text = re.sub(r'[^\u4e00-\u9fa5]', '', text)
3. 专业停用词库配置
# 基础停用词表(需准备stopwords.txt)
with open("stopwords.txt", "r", encoding="utf-8") as f:
base_stopwords = set([line.strip() for line in# 添加政治文档专用停用词
report_stopwords = {"加强", "推进", "坚持", "全面", "提高", "实施", "加快",
"建设", "推动", "支持", "工作", "完善", "深化", "优化", "落实", "持续"}
stopwords = base_stopwords.union(report_stopwords)
4. 精准分词处理
# 添加专业术语词典
jieba.add_word("高质量发展")
jieba.add_word("共同富裕示范区")
jieba.add_word("乡村振兴")
jieba.add_word("数字经济")
jieba.add_word("碳中和")
jieba.add_word("科技创新")
# 执行分词与过滤
seg_list = jieba.lcut(text)
filtered_words = [word for word in seg_list if len(word) > 1 and word not in stopwords]
5. 词频统计与分析
# 统计高频词汇TOP25
word_counts = Counter(filtered_words)
print("高频词汇TOP25:")
for word, count in word_counts.most_common(25):
print(f"{word}: {count}")
6. 可视化词云生成
# 配置词云参数
wc = WordCloud(
font_path="msyh.ttc", # 微软雅黑字体
background_color="white",
width=1200,
height=800,
max_words=150,
collocations=False, # 避免词组重复
prefer_horizontal=0.9 # 横向排版优化
)
# 生成并保存词云
wc.generate_from_frequencies(word_counts)
plt.figure(figsize=(15, 10))
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.savefig('report_analysis.png', dpi=300) # 高清输出
plt.show()
三、技术亮点解析
1. 专业术语处理
通过jieba.add_word()
添加政策领域专有词汇,确保分词准确性。例如:
• “共同富裕示范区”(完整保留政策概念)
• “碳中和”(避免拆分为"碳/中和")
2. 停用词双保险策略
• 通用停用词库:过滤常见无意义词汇
• 定制政策停用词:去除高频但低信息量的动词(如"推进"、“加强”)
3. 词云优化技巧
• collocations=False
:避免生成"发展-战略"等重复词组
• prefer_horizontal=0.9
:提升横向显示比例,符合中文阅读习惯
• dpi=300
:输出高清图像,满足印刷级需求
四、成果展示示例
高频词汇TOP25示例:
排名 | 关键词 | 出现次数 |
---|---|---|
1 | 发展 | 104 |
2 | 政策 | 53 |
3 | 经济 | 41 |
4 | 政府 | 31 |
5 | 创新 | 30 |
5 | 服务 | 30 |
7 | 国家 | 29 |
8 | 改革 | 28 |
9 | 就业 | 26 |
10 | 高质量发展 | 25 |
10 | 产业 | 25 |
12 | 社会 | 24 |
12 | 领域 | 24 |
12 | 中国 | 24 |
15 | 增长 | 23 |
15 | 保障 | 23 |
15 | 战略 | 23 |
15 | 企业 | 23 |
19 | 体系 | 22 |
19 | 重点 | 22 |
19 | 风险 | 22 |
22 | 国际 | 21 |
22 | 提升 | 21 |
22 | 地区 | 21 |
22 | 投资 | 21 |
词云效果图
作者:LY.Run