第一、理論準備
1 讀取圖片背景
bimg = imread(imgFilePath)
2 獲取圖片顏色
bimgColors=ImageColorGenerator(bimg)
3 重製詞雲的顏色
wordcloud.recolor(color_func=bimgColors)
第二、案例代碼實踐
# 讀取文件的內容
import codecs;
content=[]
f=codecs.open("D:\\database\\python\\2.5\\紅樓夢.txt",'r','utf-8')
content=f.read()
f.close()
#分詞
import jieba;
import pandas;
segments=[]
jieba.load_userdict(
'D:\\database\\python\\2.5\\紅樓夢詞庫.txt')
segs =jieba.cut(content)
for seg in segs:
if len(seg) >1 :
segments.append(seg);
segmentDF=pandas.DataFrame({'segment':segments})
# 移除停用詞
stopwords= pandas.read_csv(
'D:\\database\\python\\2.5\\StopwordsCN.txt',
encoding='utf-8',
index_col=False,
quoting=3,
sep="\t")
segmentDF=segmentDF[
~segmentDF.segment.isin(stopwords.stopword)]
wystopword=pandas.Series([
'之', '其', '或', '亦', '方', '於', '即', '皆', '因', '仍', '故',
'尚', '呢', '了', '的', '着', '一', '不', '乃', '呀', '嗎', '咧',
'啊', '把', '讓', '向', '往', '是', '在', '越', '再', '更', '比',
'很', '偏', '別', '好', '可', '便', '就', '但', '兒',
'來', '去', '道', '笑', '說',
#空格
' ', ''])
segmentDF=segmentDF[
~segmentDF.segment.isin(wystopword)]
# 詞頻統計
import numpy;
segstat=segmentDF.groupby(
by="segment")["segment"].agg({
"計數":numpy.size
}).reset_index().sort_values(
"計數",ascending=False
)
segstat.head(100);
# 繪製詞雲
from wordcloud import WordCloud
import matplotlib.pyplot as plt
wordcloud = WordCloud(
font_path='D:\\database\\python\\2.5\\simhei.ttf',
background_color="black")
words = segstat.set_index('segment').to_dict()
wordcloud.fit_words(words['計數'])
plt.imshow(wordcloud)
plt.show(wordcloud)
plt.close();
# 詞雲美化
from scipy.misc import imread
from wordcloud import WordCloud,ImageColorGenerator
import matplotlib.pyplot as plt
bimg=imread("D:\\database\\python\\2.5\\賈寶玉.png")
wordcloud = WordCloud(
mask=bimg,
font_path='D:\\database\\python\\2.5\\simhei.ttf',
background_color="white")
wordcloud=wordcloud.fit_words(words['計數'])
bimgColor=ImageColorGenerator(bimg)
plt.axis("off") # 不顯示座標標題
plt.imshow(wordcloud.recolor(color_func=bimgColor))
plt.show()
# 詞雲美化2
from scipy.misc import imread
from wordcloud import WordCloud,ImageColorGenerator
import matplotlib.pyplot as plt
bimg=imread("D:\\database\\python\\2.5\\賈寶玉2.png")
wordcloud = WordCloud(
mask=bimg,
font_path='D:\\database\\python\\2.5\\simhei.ttf',
background_color="white")
wordcloud=wordcloud.fit_words(words['計數'])
plt.figure(
num=None,
figsize=(8,6),dpi=80,
facecolor='w',edgecolor='k')
# 分別表示 對象標記、大小、分辨率、背景顏色、邊框顏色
bimgColor=ImageColorGenerator(bimg)
plt.axis("off") # 不顯示座標標題
plt.imshow(wordcloud.recolor(color_func=bimgColor))
plt.show()