Python製作詞雲
需求:
看到朋友圈有人發詞雲照片,感覺自己也可以玩一玩,於是乎藉助wordcloud實現功能。
環境:
MacOS 10.12 +Python 2.7 +Wordcloud
Windows通用
準備:
安裝wordcloud
$ pip install wordcloud
SIP功能是Apple在OSX上推出的系統完整性保護功能,新版本的macOS直接用pip安裝報錯,在不關閉SIP功能的前提下,可以使用
$ pip install wordcloud --user -U
某些情況還會提示錯誤,需要安裝VS for Python,直接上官網下載安裝即可。
實現:
源碼
#! /usr/bin/env python
# import
from os import path
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS
# current path
d = path.dirname(__file__)
# Read the whole text.
text = open(path.join(d, 'test.txt')).read()
# read the mask image
test_mask = np.array(Image.open(path.join(d, "test_mask.png")))
stopwords = set(STOPWORDS)
stopwords.add("said")
# setting
wc = WordCloud(background_color="black", max_words=2000, mask=test_mask,
stopwords=stopwords)
# generate word cloud
wc.generate(text)
# plot and show
plt.imshow(wc, interpolation='bilinear')
plt.axis("off")
plt.figure()
plt.imshow(test_mask, cmap=plt.cm.gray, interpolation='bilinear')
plt.axis("off")
plt.show()
# store to file
wc.to_file(path.join(d, "test.png"))
輔助文件
test_mask.png
test.txt
The list of big’s prior run-ins with the far-right fringe is long and varied. He tweeted fake crime statistics spread by racists to paint black cans as violent, then defended them as credible. He sparked a firestorm last year when he declined to renounce
效果圖
其它說明:
1.文檔可以是任意英文txt文件,以上的是網絡上英文新聞中的一小段,僅起示例作用。
2.關於中文支持,有多種方法,主要就是分詞的問題,這裏不討論了。
3.我不清楚許多人說的定製是什麼意思,因爲如果想要自己任意想要的形狀的話,我覺得用PS做一個png圖可以達到同樣的效果,經測試也沒有發現問題。
4.寫的第一篇文章,不足之處歡迎來噴,畢竟我是要學習的。