Python3:执代码之笔,书词云华章
Reasoned for a couple of seconds
这段代码生成了一个基于文本文件内容的中文词云,并且通过自定义的背景图来影响词云的颜色。下面是这段代码的逐步解析以及详细注释:
from os import path
from imageio import imread # 更新imread来源
import matplotlib.pyplot as plt
import jieba
from wordcloud import WordCloud, ImageColorGenerator
# 路径配置
d = path.dirname(__file__) # 确保在IDE中运行时路径正确
back_coloring_path = "New folder/alice_color.jpg" # 背景图路径
text_path = 'New folder/alice.txt' # 文本文件路径
font_path = r'C:\Users\BCY\Desktop\New folder\MFJinHei_Noncommercial-Regular.otf' # 中文字体路径
stopwords_path = r'C:\Users\BCY\Desktop\New folder\stopwords1893.txt' # 停用词表路径
imgname1 = "WordCloudDefautColors.png" # 默认颜色的词云图名称
imgname2 = "WordCloudColorsByImg.png" # 通过背景图颜色生成的词云图名称
# 加载用户词典(可选)
my_words_list = ['中国人'] # 添加自定义词汇到jieba词典中
for word in my_words_list:
jieba.add_word(word)
# 读取背景图
back_coloring = imread(path.join(d, back_coloring_path)) # 读取背景图片,用作词云的形状和颜色参考
# 初始化词云对象
wc = WordCloud(
font_path=font_path, # 设置中文字体
background_color="white", # 设置背景颜色为白色
max_words=2000, # 限制词云中最多展示的单词数
mask=back_coloring, # 设置词云的背景形状
max_font_size=100, # 设置最大字体大小
random_state=42, # 设置随机种子,确保每次生成相同的词云
width=1000, height=860, margin=2 # 设置生成的词云图像的大小和边距
)
# 读取文本并进行分词处理
def jiebaclearText(text):
mywordlist = []
seg_list = jieba.cut(text, cut_all=False) # 使用jieba进行精确模式分词
liststr = "/ ".join(seg_list) # 将分词后的内容连接成一个字符串
# 读取停用词(指定编码)
with open(stopwords_path, 'r', encoding='utf-8') as f_stop:
f_stop_seg_list = f_stop.read().splitlines() # 读取停用词文件并按行存储为列表
# 过滤停用词
for myword in liststr.split('/'):
word = myword.strip() # 去掉空格
if word not in f_stop_seg_list and len(word) > 1: # 排除停用词和长度为1的词
mywordlist.append(word) # 将有效词加入结果列表
return ' '.join(mywordlist) # 返回处理后的文本
# 处理文本
with open(path.join(d, text_path), 'r', encoding='utf-8') as f:
text = f.read() # 读取文本内容
text = jiebaclearText(text) # 处理文本,进行分词和停用词过滤
# 生成词云
wc.generate(text) # 根据处理后的文本生成词云
# 显示默认颜色词云
plt.figure(figsize=(10, 8)) # 设置画布大小
plt.imshow(wc, interpolation='bilinear') # 显示词云图
plt.axis("off") # 关闭坐标轴显示
plt.savefig(path.join(d, imgname1), bbox_inches='tight') # 保存第一张图,名称为WordCloudDefautColors.png
plt.show() # 显示词云图
# 根据背景图颜色生成词云
image_colors = ImageColorGenerator(back_coloring) # 使用背景图的颜色来生成词云
plt.figure(figsize=(10, 8))
plt.imshow(wc.recolor(color_func=image_colors), interpolation='bilinear') # 使用背景图的颜色重新着色词云
plt.axis("off")
plt.savefig(path.join(d, imgname2), bbox_inches='tight') # 保存第二张图,名称为WordCloudColorsByImg.png
plt.show() # 显示第二张词云图
代码解析
路径配置:
代码开始时配置了背景图片、文本文件、字体、停用词文件的路径。确保文件路径正确,并适应运行环境。
自定义字典:
使用
jieba.add_word()
方法将自定义词汇(如“中国人”)添加到jieba
的分词词典中,确保在分词时该词能够被正确识别。
背景图片读取:
imread
方法加载背景图,用作词云的形状和颜色参考。
词云对象初始化:
使用
WordCloud
类初始化词云对象,设置了一些参数:font_path:指定中文字体,确保中文能够正确显示。
background_color:词云的背景颜色设置为白色。
mask:将背景图用作词云的形状。
max_words:限制词云最多展示的单词数为 2000。
width 和 height:设置词云图的宽高。
文本处理:
使用
jieba.cut()
对文本进行分词。通过读取停用词文件(如“的”,“和”等)来去除无意义的常用词。
过滤掉长度为 1 的词(如标点符号)和停用词。
生成词云:
使用
wc.generate(text)
根据处理后的文本生成词云。
词云显示与保存:
默认颜色词云:显示和保存为
WordCloudDefautColors.png
。根据背景图颜色生成的词云:使用背景图的颜色重新着色词云,并保存为
WordCloudColorsByImg.png
。
结果
代码将生成两个词云图:
默认颜色的词云。
使用背景图颜色生成的词云。
评论