本文中的所有示例代碼及素材均在 github 項(xiàng)目「shijiu_wordcloud」的 wordcloud2 文件夾中。
python詞云模塊的安裝
制作詞云的主要模塊為 wordcloud,另外,要使用 jieba 庫(kù)切割中文句子,用 imageio 讀入圖片。在命令行中執(zhí)行以下命令即可安裝:
pip install wordcloud jieba imageio
制作圖片狀詞云
關(guān)鍵點(diǎn)在于利用
- 利用
imageio.imread()讀入圖片內(nèi)容 - 設(shè)置 WordCloud 的
mask參數(shù)
# example1.py
from wordcloud import WordCloud
# 導(dǎo)入 imageio 模塊的 imread 函數(shù)來(lái)讀取圖片內(nèi)容
from imageio import imread
# 讀取圖片內(nèi)容
mk = imread('素材\\五角星.png')
# 設(shè)置 mask 參數(shù)以獲得圖片狀詞云。另外,設(shè)置了 repeat 參數(shù)使得一個(gè)詞重復(fù)顯示以填滿圖片
wc = WordCloud(background_color='white', repeat=True, mask=mk)
wc.generate('star')
wc.to_file('詞云輸出\\mask.png')

值得注意的是,如果圖片背景不是白色或者透明,則依然會(huì)有文字填充。
勾勒?qǐng)D片輪廓
勾勒?qǐng)D片輪廓只需通過 contour_width 參數(shù)設(shè)置輪廓線寬度,contour_color 參數(shù)設(shè)置輪廓線顏色。
# example2.py
from wordcloud import WordCloud
from imageio import imread
import matplotlib.pyplot as plt
mk = imread('素材\\belle.png')
# 設(shè)置 contour_width 及 contour_width
wc = WordCloud(background_color='white',
scale=10,
repeat=True,
mask=mk,
contour_width=6,
contour_color='goldenrod')
wc.generate('star')
# 使用 matplotlib.pyplot 繪制詞云和素材的對(duì)比圖
fig, axes = plt.subplots(1, 2)
axes[0].imshow(wc)
axes[1].imshow(mk)
for ax in axes:
ax.set_axis_off()
# 保存圖片,設(shè)置分辨率 dpi=300
plt.savefig('詞云輸出\\profile.png', dpi=300, bbox_inches='tight')

按圖片顏色給文字著色
需要先將圖片傳入 ImageColorGenerator 類,獲取返回的顏色函數(shù),再將此函數(shù)傳入 WordCloud 的 recolor 屬性:
# example3.py
from wordcloud import WordCloud, ImageColorGenerator
from imageio import imread
mk = imread('素材\\belle.png')
# 獲取顏色函數(shù)
image_colors = ImageColorGenerator(mk)
# 將顏色函數(shù) image_colors 傳給 recolor
wc = WordCloud(background_color='white',
scale=10,
color_func=image_colors,
repeat=True,
mask=mk)
wc.generate('star')
wc.to_file('詞云輸出\\recolor.png')

下面的例子用于對(duì)比用圖片顏色著色與默認(rèn)著色效果。在創(chuàng)建 WordCloud 對(duì)象時(shí),沒有傳顏色函數(shù)給 color_func,而是在后面調(diào)用 WordCloud 對(duì)象的 recolor() 方法傳入顏色函數(shù):
# example4.py
from wordcloud import WordCloud, ImageColorGenerator
from imageio import imread
import matplotlib.pyplot as plt
mk = imread('素材\\belle.png')
wc = WordCloud(background_color='white',
scale=20,
repeat=True,
mask=mk)
wc.generate('star')
# 利用 ImageColorGenerator 類生成顏色函數(shù)
image_colors = ImageColorGenerator(mk)
fig, axes = plt.subplots(1, 3)
# 顯示使用默認(rèn)著色方案的詞云
axes[0].imshow(wc, interpolation="bilinear")
# 用 WordCloud 的 recolor 方法根據(jù)圖片顏色重新給文字上色
axes[1].imshow(wc.recolor(color_func=image_colors), interpolation="bilinear")
# 顯示原圖片
axes[2].imshow(mk, cmap=plt.cm.gray, interpolation="bilinear")
for ax in axes:
ax.set_axis_off()
plt.savefig('詞云輸出\\recolor2.png', dpi=300, bbox_inches='tight')

指定特定詞的顏色
下面代碼中,構(gòu)建了 GroupedColorFunc 類,利用該類產(chǎn)生顏色函數(shù)。
構(gòu)建了一個(gè) color_to_words 字典,鍵名為顏色,鍵值是顯示為該顏色的詞的列表。讀者只需修改此字典即可更改詞的顏色。
將字典及默認(rèn)顏色傳入 GroupedColorFunc 類創(chuàng)建該類的實(shí)例,再將此實(shí)例傳入 WordCloud 對(duì)象的 recolor 方法即可。
# example5
# 此段代碼修改自文末的官方文檔中的示例
from wordcloud import WordCloud, get_single_color_func
# 創(chuàng)建 GroupedColorFunc 類,用于產(chǎn)生顏色函數(shù)
class GroupedColorFunc(object):
def __init__(self, color_to_words, default_color):
self.color_func_to_words = [
(get_single_color_func(color), set(words))
for (color, words) in color_to_words.items()]
self.default_color_func = get_single_color_func(default_color)
def get_color_func(self, word):
"""Returns a single_color_func associated with the word"""
try:
color_func = next(
color_func for (color_func, words) in self.color_func_to_words
if word in words)
except StopIteration:
color_func = self.default_color_func
return color_func
def __call__(self, word, **kwargs):
return self.get_color_func(word)(word, **kwargs)
# 從文件中讀入文本
with open('素材\\text.txt', 'r') as f:
text = f.read()
f.close()
wc = WordCloud(background_color='white', scale=10)
wc.generate(text)
# 創(chuàng)建顏色字典,指定詞的顏色。讀者可更改顏色、詞的列表、添加新顏色、刪除顏色等
color_to_words = {
# 下面列表中的詞顯示為 orangered 顏色
'orangered': ['beautiful', 'explicit', 'simple', 'sparse',
'readability', 'rules', 'practicality',
'explicitly', 'one', 'now', 'easy', 'obvious', 'better'],
# 面列表中的詞顯示為 blue 顏色
'blue': ['ugly', 'implicit', 'complex', 'complicated', 'nested',
'dense', 'special', 'errors', 'silently', 'ambiguity',
'guess', 'hard']
}
# 設(shè)置不在字典中的詞的顏色
default_color = 'aquamarine'
# 將字典及默認(rèn)顏色傳入以創(chuàng)建 GroupedColorFunc 實(shí)例
grouped_color_func = GroupedColorFunc(color_to_words, default_color)
# 將 GroupedColorFunc 實(shí)例傳入 recolor 方法以按指定規(guī)則著色
wc.recolor(color_func=grouped_color_func)
wc.to_file('詞云輸出\\group.png')

至此,你已經(jīng)是python詞云能手了,快去創(chuàng)作自己的詞云吧!
相關(guān)閱讀: 「python詞云入門」 「python安裝詳細(xì)教程」
參考資料
- 官方文檔:「WordCloud for Python documentation」
- b站:「詞云可視化:四行Python代碼輕松上手到精通」
- github:「amueller/word_cloud」