中/英词云制作-Python
Author: zhww
Update time:2021.02.07
Description: 中英文词云制作主要步骤、个人理解与可运行程序。
小记:终于尝试了我心念已久的词云制作,也纪念我这个寒假终于迈出了找学习状态的第一步,做出下图这个牛年祝福效果后,感觉成就感满满。在此,感谢提供了许多行之有效的参考内容的博主们,也感谢背景图片的画手大大,所有素材来源网络,如介意可联系删除。最后,希望我这篇微不足道的小教程也能带给各位一点启发。
ps : 代码优美性上本人实在是小白,最后勉强封装了一下,后续有时间会细化这个工具。
–收集祝福词做出来的新年效果(2021-02-07)
准备
python3.x版
安装:
# pip install matplotlib # 绘图
# pip install jieba # 中文文本分词
# pip install wordcloud # 词云
镜像安装(应对time out 的报错情况)
# pip install -i https://pypi.tuna.tsinghua.edu.cn/simple matplotlib # 绘图
# pip install -i https://pypi.tuna.tsinghua.edu.cn/simple jieba # 中文分词
# pip install wordcloud -i https://mirrors.aliyun.com/pypi/simple/ # 词云
参考:第三方库镜像安装
原理
在生成词云时,wordcloud默认会以空格或标点为分隔符对目标文本进行分词处理。
处理步骤:
- 文本分词处理
- 读入txt文本数据
- jieba分词处理
- 形成以空格分隔的字符串
- 文本转化为词云图片
- 创建WordCloud对象,设置参数(如背景图、停用词)
- 产生词云
- 输出为图片
英文词云
Demo Description: 无需添加字体,无需背景图片
Code1:
import matplotlib.pyplot as plt
import jieba
from os import path
from PIL import Image
import numpy as np
from wordcloud import WordCloud
# 1.读入txt文本数据
text = open(r'test.txt', "r").read()
#print(text)
# 2.结巴中文分词,生成字符串,默认精确模式,如果不通过分词,无法直接生成正确的中文词云
cut_text = jieba.cut(text)
# print(type(cut_text))
# 必须给个符号分隔开分词结果来形成字符串,否则不能绘制词云
result = " ".join(cut_text)
# print(result)
# 3.生成词云图,这里需要注意的是WordCloud默认不支持中文,所以这里需已下载好的中文字库
# 无自定义背景图:需要指定生成词云图的像素大小,默认背景颜色为黑色,统一文字颜色:mode='RGBA'和colormap='pink'
###当前文件路径
d = path.dirname(__file__)
wc = WordCloud(
# 设置字体,不指定就会出现乱码
# 设置背景色
background_color='white',
# 设置背景宽
width=600,
# 设置背景高
height=350,
# 最大字体
max_font_size=50,
# 最小字体
min_font_size=10,
mode='RGBA',
# colormap='pink'
)
# 产生词云
wc.generate(result)
# 保存图片
wc.to_file(r"wordcloud.png") # 按照设置的像素宽高度保存绘制好的词云图,比下面程序显示更清晰
# 4.显示图片
# 指定所绘图名称
plt.figure("jay")
# 以图片的形式显示词云
plt.imshow(wc)
# 关闭图像坐标系
plt.axis("off")
plt.show()
ResultSample(Ewordcloud01.png):
测试记录:
Ewordcloud01.png——不加背景图,设置横纵大小以及字体范围,不设停用词;
Ewordcloud02.png——不加背景图,设置横纵大小以及字体范围,不设停用词,增加colormap='pink’选项;
Ewordcloud02.png——加背景图,设置白色背景,官方停用词;
中文词云
Demo Description:wordcloud默认字体是不支持中文,需要添加字体,Code2使用了背景图片
Code2:
#!/usr/bin/Python
# -*- coding: utf-8 -*-
from os import path
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import jieba
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
# 创建停用词列表
def stopwordslist():
stopwords = [line.strip() for line in open('baidu_stopwords.txt', encoding='UTF-8').readlines()]
return stopwords
###当前文件路径
d = path.dirname(__file__)
# Read the whole text.
file = open(path.join(d, 'alice.txt')).read()
##进行分词
#刚开始是分完词放进txt再打开却总是显示不出中文很奇怪
default_mode =jieba.cut(file)
text = " ".join(default_mode)
alice_mask = np.array(Image.open(path.join(d, "avater.jpg")))
# stopwords = set(STOPWORDS)
# 创建一个停用词列表
stopwords = set(stopwordslist