如何使用 Python 制作文字云
· 5 分钟阅读
这篇文章在教学如何使用 Python 读取中文文档,产生像下图的文字云
文字云套件 :WordCloud
这次使用的套件为 WordCloud
基本型: 英文
首先先到 CNN 截取了一段新闻,将内容存成 txt 档,测试程式如下
from wordcloud import WordCloud, STOPWORDS
import matplotlib.pyplot as plt
# Read the whole text.
txtfile = "c:/test-wordcloud/cnn.txt" # 刚才下载存的文字档
text = open(txtfile,"r",encoding="utf-8").read()
# Generate a word cloud image
wordcloud = WordCloud().generate(text)
# 绘图
plt.figure()
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
plt.show()
产生文字云如下
这篇文章主要在讲乌俄战争的事,出现最多次的为 weapon 和 Russia 这两个字,所以可以看出文字云中这两个字的字型最大
增加 Mask:英文
但一般的需求都是会有张底图,所以先去网路捉了张底图,根据官网做了些修改,测试程式如下
from wordcloud import WordCloud, STOPWORDS
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
# Read the whole text.
txtfile = "c:/test-wordcloud/cnn.txt" # 刚才下载存的文字档
pngfile = "c:/test-wordcloud/cloud.jpg" # 刚才下载存的底图
text = open(txtfile,"r",encoding="utf-8").read()
alice_mask = np.array(Image.open(pngfile))
# Generate a word cloud image
wordcloud = WordCloud(background_color="white", mask=alice_mask, contour_width=3, contour_color='steelblue').generate(text)
# 绘图
plt.figure()
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
plt.show()
其实主要只差了这一行,多加几个参数而已
wordcloud = WordCloud(background_color="white", mask=alice_mask, contour_width=3, contour_color='steelblue').generate(text)
产生文字云如下
这张图看起来就符合需求多了,但是这个程式码只适用于英文,原因是中文有断词问题
中文断词套件:Jieba
中文断词套件最有名的就是 Jieba
这篇文章不打算仔细的介绍 Jieba 的原理,有空的话再整理篇独立的文章吧