Python詞雲wordcloud——根據詞語生成圖像

wordcloud作者github應用實例:
https://github.com/amueller/word_cloud/blob/master/examples/masked.py
官網:https://amueller.github.io/word_cloud/generated/wordcloud.WordCloud.html
內容包括:生成中文詞雲、英文詞雲、根據單詞出現頻率生成詞雲
中文

參數設定

WordCloud可以直接pip安裝,在Anaconda裏python -m pip install SomePackage(包名)就可以安裝。
WordCloud()部分常用參數
font_path:string字體,中文需要設定中文字體
width:int (default=400)寬
height:int (default=200)高
prefer_horizontal:float (default=0.90)水平與豎直排版比,小於1則將不合適水平詞語豎直顯示,大於1則只水平
mask:nd-array or None (default=None) 背景圖,white (#FF or #FFFFFF)區域不能放詞。
scale:float (default=1) 對大型詞雲用scale縮放比放大尺寸生成速度更快,但可能模糊
max_words:number (default=200)最大詞量
stopwords:set of strings or None如果不設定停止詞則使用默認STOPWORDS
background_color:color value (default=”black”)設置背景色
mode:string (default=”RGB”)設定RGBA則背景變爲透明

wordcloud.WordCloud方法
我使用過的:
generate(text)Generate wordcloud from text.生成詞雲
to_file(filename)Export to image file. 保存圖片
recolor([random_state, color_func, colormap])Recolor existing layout.對已有的詞雲重新配色(比重新生成某種顏色的詞雲快)
process_text(text)Splits a long text into words, eliminates the stopwords.返回統計文本中單詞頻率的dict
generate_from_frequencies(frequencies[, …])Create a word_cloud from words and frequencies.根據頻率生成詞雲
沒用過的:
fit_words(frequencies) Create a word_cloud from words and requencies.
generate_from_text(text)Generate wordcloud from text.
to_array()Convert to numpy array.

應用

注意:
1、詞雲每次隨機生成,再次運行則生成新詞雲。
2、wordcloud.to_file(‘myfig.png’)的方法生成詞雲比plt.savefig更清楚,後者不能反映詞雲設置的大小等參數。
以下代碼中text文件選擇了分別包含林俊杰對的時間點的中英文歌詞的兩個txt,掩碼圖片選了一張白底png圖片。

無背景詞雲
from wordcloud import WordCloud
import matplotlib.pyplot as plt

text = open('C:/Users/Violette/Desktop/data/As I believe.txt').read()#讀入文本
wordcloud=WordCloud()
wordcloud.generate(text)
image=wordcloud.to_image()
plt.imshow(image) # 顯示圖片
plt.axis('off') # 不顯示座標軸
plt.savefig('C:/Users/Violette/Desktop/data/myfig.png')
plt.show()

無背景圖片

無背景頻率詞雲

統計文本中單詞出現的頻率,頻率越大的單詞詞雲中字體越大。
用process_word()方法統計單詞頻率,返回dict
generate_from_frequencies(dict)方法生成頻率詞雲

from wordcloud import WordCloud
import matplotlib.pyplot as plt

text = open('C:/Users/Violette/Desktop/data/As I believe.txt').read()#讀入文本
wordcloud=WordCloud()
process_word=WordCloud.process_text(wordcloud,text)
print(process_word)
wordcloud.generate_from_frequencies(process_word)
image=wordcloud.to_image()
plt.imshow(image) # 顯示圖片
plt.axis('off') # 不顯示座標軸
plt.savefig('C:/Users/Violette/Desktop/data/myfig.png')
plt.show()

在歌詞中出現頻率最高的詞是’believe’: 8,‘know’: 8所以這兩個詞在圖像中最大:
頻率圖片

背景詞雲

在圖片mask上生成詞雲,多增加一步讀入背景圖並將圖片轉換爲數組:
需要import的文件:
import numpy as np
from PIL import Image
需要將讀取圖像轉爲數組格式來進行後續操作:
mask_image=np.array(Image.opern(‘mask.png’))
wordcloud=WordCloud(background_color=“white”,width=600, max_words=100, mask=mask_image).generate(text)

如果需要轉換顏色爲mask顏色則:
from wordcloud import ImageColorGenerator
image_colors = ImageColorGenerator(mask_image)#提取顏色
wordcloud.recolor(color_func=image_colors)#重置顏色函數
使用recolor重置顏色,可以將詞雲在mask對應位置的字體顏色變爲mask圖片上的顏色。
完整代碼:

from wordcloud import WordCloud, ImageColorGenerator#用於提取圖片顏色
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

text = open('C:/Users/Violette/Desktop/data/As I believe.txt').read()#讀入文本

images=Image.open('C:/Users/Violette/Desktop/data/heart.png')#讀入背景圖
mask_image=np.array(images)#圖片轉化爲數組
#等價於mask_image = np.array(Image.open('C:/Users/Violette/Desktop/data/heart.png'))

wordcloud=WordCloud(background_color="white",width=600, max_words=100, 
                    mask=mask_image).generate(text)#生成詞雲圖

#提取mask顏色
image_colors = ImageColorGenerator(mask_image)
#wordcloud.recolor(color_func=image_colors)#重置顏色函數

image=wordcloud.to_image()

# 顯示圖像
fig,axes = plt.subplots(1,2)
axes[0].imshow(wordcloud)#不設置顏色
axes[1].imshow(wordcloud.recolor(color_func=image_colors))#將詞雲顏色設置爲mask的顏色
for ax in axes:
    ax.set_axis_off()#給每幅圖都去座標軸
plt.savefig('C:/Users/Violette/Desktop/data/myfig.png')
plt.show()

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-21SK24Zj-1572265819170)(en-resource://database/1068:0)]

中文詞雲

關於讀中文txt參考原文鏈接:https://blog.csdn.net/jingyi130705008/article/details/71513984
文中提到txt使用utf8編碼的時候會默認在文件開頭插入三個不可見字符,python定義爲codecs.BOM_UTF8。
對python2.7:
讀中文txt時必須先比較前三個字符與codecs.BOM_UTF8,如果一樣就刪除前三個字符然後再decode。

import codecs
data = open("Test.txt").read()
if data[:3] == codecs.BOM_UTF8:
    data = data[3:]
    print data.decode("utf-8")

對python3:
讀取文件時解碼可以直接encoding=‘gbk’

調用WordCloud時,設定字體參數font_path

text = open('C:/Users/Violette/Desktop/data/chinese.txt',encoding='gbk').read()#讀入txt格式中文文本
text = open('C:/Users/Violette/Desktop/liao_excel/classify_model1.csv',encoding='utf-8').read()#csv格式中文文本
wordcloud=WordCloud(font_path='C:/Windows/Fonts/simfang.ttf',background_color="white",width=600, max_words=100, mask=mask_image).generate(text)#生成詞雲圖時需要設定字體參數font_path

中文

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章