
from wordcloud import WordCloud, ImageColorGenerator
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
# 加载中国地图轮廓图
mask_image_path = r"D:\中国地图.png"
mask_image = Image.open(mask_image_path).convert('L') # 转换为灰度图像
mask = np.array(mask_image)
# 从指定文件路径读取文本数据
text_file_path = r"D:\政府工作报告.txt"
with open(text_file_path, 'r', encoding='utf-8') as file:
text = file.read()
# 设置字体路径以支持中文显示
font_path = 'simhei.ttf' # 如果 simhei.ttf 不在当前目录,请提供完整路径
# 创建词云对象并生成词云
wordcloud = WordCloud(
font_path=font_path, # 设置支持中文的字体路径
background_color="white",
mask=mask,
width=1600,
height=800,
max_words=200 # 设置最大词汇数为20
).generate(text)
# 显示词云图
plt.figure(figsize=(10, 5))
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off") # 关闭坐标轴
plt.show()