一、准备
1.关键词文本文件
2024年政府工作报告关键词.txt
2.mask遮罩图
China.png
中间发现需要用白色背景黑色内容的图片
如mask.png
二、词云图
1.导入所需的第三方库
from PIL import Image
import numpy as np
import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt
2.读取文本文件
# 读取政府工作报告文本
with open("2024年政府工作报告关键词.txt", "r", encoding="utf-8") as file:
report_text = file.read()
# 使用 jieba 进行中文分词
words = jieba.lcut(report_text)
# 将分词结果用空格连接起来,形成字符串
text = " ".join(words)
3.读取遮罩图片
# 读取遮罩图片
mask_image = Image.open("mask.png") # 确保路径正确
# 将遮罩图片转换为 NumPy 数组
mask = np.array(mask_image)
# 获取遮罩图片的尺寸
width, height = mask_image.size
4.生成词云图
# 使用 wordcloud 库生成词云
wordcloud = WordCloud(
background_color="white", # 背景颜色
mask=mask, # 使用遮罩图片数组
font_path='C:/Windows/Fonts/simsun.ttc', # 适用于常见的中文字体
max_words=200, # 限制单词数量
width=width, # 设置词云宽度与遮罩图片相同
height=height # 设置词云高度与遮罩图片相同
).generate(text)
# 显示词云图片
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off") # 关闭坐标轴
plt.show()
三、完整代码及运行截图
1.完整代码
from PIL import Image
import numpy as np
import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# 读取政府工作报告文本
with open("2024年政府工作报告关键词.txt", "r", encoding="utf-8") as file:
report_text = file.read()
# 使用 jieba 进行中文分词
words = jieba.lcut(report_text)
# 将分词结果用空格连接起来,形成字符串
text = " ".join(words)
# 读取遮罩图片
mask_image = Image.open("mask.png") # 确保路径正确
# 将遮罩图片转换为 NumPy 数组
mask = np.array(mask_image)
# 获取遮罩图片的尺寸
width, height = mask_image.size
# 使用 wordcloud 库生成词云
wordcloud = WordCloud(
background_color="white", # 背景颜色
mask=mask, # 使用遮罩图片数组
font_path='C:/Windows/Fonts/simsun.ttc', # 适用于常见的中文字体
max_words=200, # 限制单词数量
width=width, # 设置词云宽度与遮罩图片相同
height=height # 设置词云高度与遮罩图片相同
).generate(text)
# 显示词云图片
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off") # 关闭坐标轴
plt.show()