1. 引言

词云图可以让我们方便地识别出文本中的关键词,其中单词的大小代表它们的频率。有了这个,我们甚至在阅读之前就可以很好地了解文本的内容。虽然有很多免费的工具可以在线制作文字云,但我们可以使用万能的Python来定制个性化的词云图。

在本文中,我们将使用第三方Python库stylecloud,有了该库,可以通过简短的几行代码来制作漂亮的词云图。如下所示:

#yyds干货盘点#在Python中如何方便的制作个性化的词云图_词云

闲话少说,我们直接开始吧。 :)


2. 举个栗子

接下来,我们将用来制作词云图的文本是偶像乔布斯在斯坦福大学演讲的一部分。​​点击这里​​可以获得对应的 .txt 文件或使用任何其他的文本来制作你自己的词云图。

2.1 安装stylecloud库

这里我们可以直接使用pip来安装该词云库,代码如下:

pip3 install stylecloud

2.2 生成词云图

接着我们可以使用stylecloud.gen_stylecloud() 方法来生成词云图,通过传递相应的文本 .txt 文件的路径和生成词云的图标样式。

在​​网站​​上,我们可以方便的找到可用于 stylecloud 的图标样式列表。在此示例中,我选择了一个苹果作为图标。代码如下:


import stylecloud
stylecloud.gen_stylecloud(file_path='SJ-Speech.txt',
icon_name="fas fa-apple-alt")

上述代码运行后,在当前python文件目录下生成以png格式保存词云图,如下所示:

#yyds干货盘点#在Python中如何方便的制作个性化的词云图_数据可视化_02


2.3 美化显示效果

仔细观察gen_stylecloud函数的相关参数,我们可以控制背景颜色、单词的颜色、输出文件的名称等。为此,我们查看下面的代码:

stylecloud.gen_stylecloud(file_path='SJ-Speech.txt',
icon_name='fas fa-apple-alt',
colors='white',
background_color='black',
output_name='apple.png',
collocations=False)

运行结果如下:

#yyds干货盘点#在Python中如何方便的制作个性化的词云图_python编程_03


2.4 处理停用词

我们可以使用stop_words库来处理文本中的停用词,可以使用​​pip install stop_words​​来安装该库。有了停用词列表,我们也可以将其传递给在gen_stylecloud函数中的custom_stopwords参数。

样例代码如下:

from stop_words import get_stop_words
stop_words = get_stop_words('english')
stylecloud.gen_stylecloud(file_path='SJ-Speech.txt',
icon_name='fas fa-apple-alt',
palette='cartocolors.qualitative.Pastel_3',
background_color='black',
output_name='apple.png',
collocations=False,
custom_stopwords=stop_words)

上述代码的运行结果如下:

#yyds干货盘点#在Python中如何方便的制作个性化的词云图_词云_04


2.5 使用自定义背景图像

在上述网站上有数百个免费图标可用于 stylecloud,但是但有时我们可能希望使用自己的图像来为创建更加个性化的词云图。此时,我们可以使用PIL库来读取图像,使用matplotlib来绘制我们的图像,使用wordcloud来制作对应的词云图。

下述代码中使用蝙蝠的图案来生成对应的词云图,代码如下:

from wordcloud import WordCloud, ImageColorGenerator
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
# create a mask based on the image we wish to include
my_mask = np.array(Image.open('batman-logo.png'))
# create a wordcloud
wc = WordCloud(background_color='white',
mask=my_mask,
collocations=False,
width=600,
height=300,
contour_width=3,
contour_color='black',
stopwords=stop_words)

with open('SJ-Speech.txt',encoding='gb18030',errors='ignore') as txt_file:
texto = txt_file.read()
wc.generate(texto)
image_colors = ImageColorGenerator(my_mask)
wc.recolor(color_func=image_colors)

plt.figure(figsize=(20, 10))
plt.imshow(wc, interpolation='bilinear')
plt.axis('off')
wc.to_file('wordcloud2.png')
plt.show()

运行结果如下:

#yyds干货盘点#在Python中如何方便的制作个性化的词云图_数据可视化_05

3. 总结

本文详细介绍了如何使用stylecloud库来绘制各种样式的词云图,以突出显示文本中相应的关键词,并给出了定制化改进显示效果的样例代码。

您学废了吗?


4. 参考

​参考链接一​

​参考链接二​

​参考链接三​

#yyds干货盘点#在Python中如何方便的制作个性化的词云图_数据可视化_06

关注公众号《AI算法之道》,获取更多AI算法资讯。


关注公众号,后台回复 stylecloud,即可获取源代码。