2022年政府工作报告词频分析
a.获取网页文件(捕获异常)
b.筛选有用目标
c.写入文件
d.文件预处理:去除无用字符及停用词汇
e.词频统计,建立字典,按词频排序并输出
f.绘制词云
from bs4 import BeautifulSoup
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import requests
import jieba
url=“http://www.gov.cn/premier/2022-03/12/content_5678750.htm”#2022年政府工作报告网址
try:
response=requests.get(url)
response.raise_for_status()# 如果响应状态码不是200,主动抛出异常
html=response.content.decode(“utf-8”)#爬取网页文件
except requests.requestException as e:
print(e) #打印异常信息内容
soup=BeautifulSoup(html,“html.parser”) #html文件解析
content=soup.find(“div”,class_=“pages_content”).text #筛选目标
fileName=“2022政府工作报告.txt”
with open(fileName,“w”) as f:
f.write(content)
#print(content)
with open(fileName,‘r’) as f1:
text1=f1.read()
#去除特殊符号
for ch in ‘‘ ,。“”、:;()!-——《》’’:
text1=text1.replace(ch,’’)
#直接使用分词工具进行分词
words=jieba.cut(text1)
#去除停用词,“停用词库.txt”为事先保存好的停用库文件
stopwords=[]
with open(“停用词库.txt”,“r”,encoding=“utf-8”) as stop:
stopWords=stop.read()
#开始词频统计
counts={}
for word in words:
if word not in stopWords: #不是停用词库的才统计
counts[word]=counts.get(word,0)+1
#将字典转换为列表
items=list(counts.items())
#按列表元素中的第二项从大到小排序
items.sort(key=lambda x:x[1],reverse=True)
#按词频由高到底输出前20个词汇
for i in range(20):
word,count=items[i]
print("{0:<10}{1:>5}".format(word,count))
wordStr=word + ’ ’
w=WordCloud(font_path=“msyh.ttc”,max_words=20)
#w=WordCloud().generate(wordStr) #生成WordCloud对象
w=w.fit_words(counts)#字典类型进行赋值
w.to_file(“2022政府工作报告词云.png”) #保存词云图片
plt.imshow(w)# 对图像进行处理,并显示其格式
plt.axis(‘off’)# 隐藏词云图片的坐标边界
plt.show()#显示处理后的词云图片
词频统计:
发展 127
建设 68
推进 67
支持 59
政策 45
经济 44
企业 43
推动 42
加快 38
改革 35
就业 34
服务 34
实施 34
政府 33
创新 33
工作 30
保障 30
加大 28
完善 28
国家 25



