一直覺(jué)得WordCloud挺好玩的,今天偶然看到一篇關(guān)于WordCloud的博客,于是試了一下。沒(méi)想到遇到一串問(wèn)題,記錄下來(lái),以饗跟我一樣探奇中的同學(xué)們。
第一步:當(dāng)然是安裝,我只用了最簡(jiǎn)單的方法
pip install wordcloud
第二步,來(lái)個(gè)demo吧。BTW:下面這段代碼來(lái)源互聯(lián)網(wǎng),非原創(chuàng)
from os import path
from scipy.misc import imread
import matplotlib.pyplot as plt
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
# 獲取當(dāng)前文件路徑# __file__ 為當(dāng)前文件, 在ide中運(yùn)行此行會(huì)報(bào)錯(cuò),可改為# d = path.dirname('.')d = path.dirname(__file__)
# 讀取文本 alice.txt 在包文件的example目錄下
#內(nèi)容為
"""
Project Gutenberg's Alice's Adventures in Wonderland, by Lewis Carroll
This eBook is for the use of anyone anywhere at no cost and with
almost no restrictions whatsoever. ?You may copy it, give it away or
re-use it under the terms of the Project Gutenberg License included
with this eBook or online at www.gutenberg.org
"""
text = open(path.join(d,'alice.txt')).read()
# read the mask / color image
# taken from http://jirkavinse.deviantart.com/art/quot-Real-Life-quot-Alice-282261010
# 設(shè)置背景圖片
alice_coloring = imread(path.join(d,"alice_color.png"))
wc = WordCloud(background_color="white", #背景顏色
max_words=2000, #詞云顯示的最大詞數(shù)
mask=alice_coloring, #設(shè)置背景圖片
stopwords=STOPWORDS.add("said"),
max_font_size=40, #字體最大值
random_state=42)
# ?生成詞云, 可以用generate輸入全部文本(中文不好分詞),也可以我們計(jì)算好詞頻后使用generate_from_frequencies函數(shù)
wc.generate(text)
# wc.generate_from_frequencies(?txt_freq)
# txt_freq例子為[('詞a', 100),('詞b', 90),('詞c', 80)]
# ?從背景圖片生成顏色值
image_colors = ImageColorGenerator(alice_coloring)
# 以下代碼顯示圖片
plt.imshow(wc)
plt.axis("off") # 繪制詞云
plt.figure() # recolor wordcloud and show
# we could also give color_func=image_colors directly in the constructor
plt.imshow(wc.recolor(color_func=image_colors))
plt.axis("off") # 繪制背景圖片為顏色的圖片plt.figure()
plt.imshow(alice_coloring, cmap=plt.cm.gray)
plt.axis("off")
plt.show()
#保存圖片
wc.to_file(path.join(d,"名稱.png"))
BTW:其實(shí)我想把上面的代碼使用代碼專用格式顯示,但是簡(jiǎn)書(shū)好像不支持這個(gè)。。。然后我想,是不是應(yīng)該換到CSDN上了呢?
回到正題繼續(xù),把上面的代碼敲進(jìn)去之后,一堆麻煩來(lái)了,最精彩的情節(jié)從此展開(kāi)。
第一個(gè)麻煩:運(yùn)行demo的時(shí)候提示scipy.misc.imread函數(shù)不存在
好吧,不記得什么時(shí)候裝scipy的時(shí)候就費(fèi)了老鼻子勁了,所以自從裝上之后我一直以為scipy是好好的,因?yàn)閕mport scipy是成功的,沒(méi)想到還能發(fā)生這樣的事情。
首先嘗試 pip install scipy --upgrade
運(yùn)行到一部分的時(shí)候提示找不到fortran的編譯器。
到https://gcc.gnu.org/wiki/GFortranBinaries#MacOS 這個(gè)地址下載一個(gè)編譯好的可執(zhí)行文件(我用的mac,用其他操作系統(tǒng)的同學(xué)也可以在上面這個(gè)網(wǎng)站找到適合的可執(zhí)行文件),安裝之后重新運(yùn)行:
pip install scipy --upgrade
終于work了,雖然中間還是報(bào)了很多很多warning
裝完之后from scipy import misc --> dir(misc) ,仍然沒(méi)有發(fā)現(xiàn)imread
繼續(xù)百度,發(fā)現(xiàn)似乎是缺少PIL和Pillow兩個(gè)包,于是
pip install PIL
pip install Pillow
然后再次from scipy import misc --> dir(misc),這回imread妥妥的躺在那里了。小小的激動(dòng)一下,第一次發(fā)現(xiàn)python還能這么玩。
今天先high到這里,下一集準(zhǔn)備把川普的就職演講做一個(gè)wordcloud。各位看官,期待的話就請(qǐng)點(diǎn)一點(diǎn)"喜歡"鼓勵(lì)一下吧。