python大作业
题目:某年度政府工作报告的词云绘制要求:利用所学知识爬取某年度政府工作报告,并进行词频排序,输出top50,在将top50绘制成词云,词云颜色可自选,形状是某年。
一、爬虫:
网络爬虫,是一种按照一定规则,自动抓取互联网信息的程序或者脚本。只要能通过浏览器访问的数据都可以通过爬虫抓取。本质是模拟浏览器打开网页,获取网页中我们想要的那部分数据。
二、爬虫步骤
1.获取数据
requests 库是 Python 中发起http请求的库,使用 text 或者 content 属性来获取网站返回的数据
text:是以字符串的形式返回数据
content:是以二进制的方式返回数据
注意:网站源代码通常会包含很多子窗口的url
,如果要读取子窗口的正文信息,可以利用正则表达式在字符串中提取到url,我这里没有使用。
import requests
# 获取网页内容
url = 'http://www.ncha.gov.cn/art/2022/3/13/art_2567_173347.html'
response = requests.get(url)
# text=response.text
# print(text)
html = response.content.decode('utf-8')
print(html)
2.解析数据
BeautifulSoup 是 Python 的一个库,最主要的功能是从网页解析数据。
from bs4 import BeautifulSoup
# 解析网页内容
soup = BeautifulSoup(html, 'html.parser')
text = soup.get_text()
3.保存数据
拿到数据之后,需要持久化到本地文件或者数据库等存储设备中。
以下为MySQL数据库为例,可以根据数据格式自行修改数据表格式
import pymysql
# 建立与MySQL数据库的连接
conn = pymysql.connect(user='root', password='123456', host='localhost', database='learn')
cursor = conn.cursor()
# 创建表格
cursor.execute("DROP TABLE IF EXISTS ") # 如果存在表则重新创建
createTab = """CREATE TABLE data( # 创建表
id INTEGER PRIMARY KEY AUTO_INCREMENT,
data CHAR(50))"""
cursor.execute(createTab) # 执行数据库语句
sql = ("INSERT INTO data "
"(TIME, data) "
"VALUES (%(TIME)s, %(data)s)")
data = {
'TIME': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
'data': str(data),
}
cursor.execute(sql, data)
conn.commit()
三、词云制作
词云,又称文字云,是文本数据的视觉表示,由词汇组成类似云的彩色图形,用于展示大量文本数据。每个词的重要性以字体大小或颜色显示,主要用来做文本内容关键词出现的频率分析,适合文本内容挖掘的可视化。词云中出现频率较高的词会以较大的形式呈现出来,出现频率较低的词会以较小的形式呈现,本质是点图,是在相应坐标点绘制具有特定样式的文字的结果。
词云的生成主要使用wordcloud 和 matplotlib库
jieba库可以实现对文本进行分割
最后剔除掉异常数据并对词频数据进行统计
import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt
这里词云形状由导入词云图背景图片决定
设置词云背景尺寸、颜色,字体等
注意:字体路径一般位于C:/Windows/Fonts/,这里以宋体为例:C:/Windows/Fonts/simsun.ttc,也可将字体文件复制到代码目录,不然容易出现字体无法显示。
# 获取词频前五十的词语和对应的词频
top50_words = dict(Counter(filtered_counter).most_common(50))
# 加载形状图片
mask = np.array(Image.open("D:/6.png"))
# 创建词云对象,并指定字体路径和字体大小
wordcloud = WordCloud(background_color='white', mask=mask, width=1600, height=800, random_state=42, font_path='C:/Windows/Fonts/simsun.ttc')
# 生成词云
wordcloud.generate_from_frequencies(top50_words)
# 随机颜色函数
def random_color_func(word=None, font_size=None, position=None, orientation=None, font_path=None, random_state=None):
r = np.random.randint(0, 256)
g = np.random.randint(0, 256)
b = np.random.randint(0, 256)
return f"rgb({r}, {g}, {b})"
# 设置词云颜色
wordcloud.recolor(color_func=random_color_func)
# 显示词云图像
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.show()
以爬取2022年政府工作报告为例
top50词频统计:
发展 127 建设 68 加强 68 推进 66 支持 59 政策 45 经济 44 企业 43 推动 42 加快 38 促进 36 政府 35 改革 35 就业 34 服务 34 实施 34 创新 33 工作 32 保障 30 加大 28 完善 28 坚持 28 继续 27 国家 25 全面 24 社会 24 强化 24 稳定 24 提升 23 落实 22 持续 21 提高 21 力度 21 能力 21 中国 21 保持 20 优化 20 做好 20 增长 19 投资 19基本 18 增强 18 深化 18 生产 18 市场 18 扩大 18 疫情 17 开展 17 监管 17 治理17
词云:

四、python代码如下:
import re
import numpy as np
import requests
from bs4 import BeautifulSoup
import jieba
from collections import Counter
from wordcloud import WordCloud
import matplotlib.pyplot as plt
from PIL import Image
# 获取网页内容
url = 'http://www.ncha.gov.cn/art/2022/3/13/art_2567_173347.html'
response = requests.get(url)
html = response.content.decode('utf-8')
# 解析网页内容
soup = BeautifulSoup(html, 'html.parser')
text = soup.get_text()
# 去除标点符号和数字
text = re.sub(r'[^\w\s]', '', text)
text = re.sub(r'\d+', '', text)
# 分词和统计词频
words = jieba.cut(text)
counter = Counter(words)
# 过滤词语长度小于2的词语
filtered_words = [word for word in counter if len(word) >= 2]
filtered_counter = {word: counter[word] for word in filtered_words}
# 输出词频前五十的词语
for word, count in Counter(filtered_counter).most_common(50):
print(word, count)
# 获取词频前五十的词语和对应的词频
top50_words = dict(Counter(filtered_counter).most_common(50))
# 加载形状图片
mask = np.array(Image.open("D:/6.png"))
# 创建词云对象,并指定字体路径和字体大小
wordcloud = WordCloud(background_color='white', mask=mask, width=1600, height=800, random_state=42, font_path='C:/Windows/Fonts/simsun.ttc')
# 生成词云
wordcloud.generate_from_frequencies(top50_words)
# 随机颜色函数
def random_color_func(word=None, font_size=None, position=None, orientation=None, font_path=None, random_state=None):
r = np.random.randint(0, 256)
g = np.random.randint(0, 256)
b = np.random.randint(0, 256)
return f"rgb({r}, {g}, {b})"
# 设置词云颜色
wordcloud.recolor(color_func=random_color_func)
# 显示词云图像
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.show()