python詞云庫wordCloud使用方法詳解(解決中文亂碼)
文章中的例子主要借鑒wordColud的examples,在文章對(duì)examples中的例子做了一些改動(dòng)。
一、wordColud設(shè)計(jì)中文詞云亂碼
使用wordColud設(shè)計(jì)詞云的時(shí)候可能會(huì)產(chǎn)生亂碼問題,因?yàn)閣ordColud默認(rèn)的字體不支持中文,所以我們只需要替換wordColud的默認(rèn)字體即可正常顯示中文。
1、中文詞云亂碼
我們使用simhei(黑體)來替換wordColud的默認(rèn)字體。
2、替換默認(rèn)字體
a、在字體文件*.tff字體文件(simhei.tff)拷貝到wordColud安裝的文件夾中,文件夾路徑:anaconda(python)-->lib-->site-packages-->wordcolud,如下圖:

其中矩形框出來的是wordColud默認(rèn)的字體,橢圓形框的是我們下載的字體。
b、修改wordcolud.py文件中的字體設(shè)置,打開改路徑下的wordcolud.py文件,找到下圖的所示的框出來的這一行(29行)
將系統(tǒng)的DroidSansMono.tff修改為simhei.tff即可。

二、wordColud示例
1、設(shè)計(jì)一個(gè)簡(jiǎn)單的圓形詞云
import numpy as np
import matplotlib.pyplot as plt
from wordcloud import WordCloud,STOPWORDS
from PIL import Image
from os import path
import matplotlib.pyplot as plt
#用來正常顯示中文
plt.rcParams["font.sans-serif"]=["SimHei"]
#用來正常顯示負(fù)號(hào)
plt.rcParams["axes.unicode_minus"]=False
import os
import random,jieba
'''
繪制單個(gè)詞一個(gè)圓形的詞云
'''
def single_wordColud():
text = "第一 第二 第三 第四"
#產(chǎn)生一個(gè)以(150,150)為圓心,半徑為130的圓形mask
x,y = np.ogrid[:300,:300]
mask = (x-150) ** 2 + (y-150) ** 2 > 130 ** 2
mask = 255 * mask.astype(int)
wc = WordCloud(background_color="white",repeat=True,mask=mask)
wc.generate(text)
#將x軸和y軸坐標(biāo)隱藏
plt.axis("off")
plt.imshow(wc,interpolation="bilinear")
plt.show()

2、以圖片形狀作為背景設(shè)計(jì)詞云

下面以蠟筆小新的這張圖片作為背景來設(shè)計(jì)一個(gè)詞云,我們通過讀取一個(gè)txt文件,文件中包含了很多段落,然后通過jieba對(duì)句子進(jìn)行分詞,去除停用詞之后,生成一張?jiān)~云的照片。
a、讀取文件內(nèi)容
使用jieba分詞后,詞之間需要通過空格進(jìn)行分割,不然在產(chǎn)生詞云的時(shí)候回變成一個(gè)詞。
'''
中文分詞
'''
def segment_words(text):
article_contents = ""
#使用jieba進(jìn)行分詞
words = jieba.cut(text,cut_all=False)
for word in words:
#使用空格來分割詞
article_contents += word+" "
return article_contents
b、讀取停用詞
停用詞包括一些標(biāo)點(diǎn)符號(hào),和一些沒有實(shí)際意義的詞,我們需要將這些詞都去除。
'''
從文件中讀取停用詞
'''
def get_stopwords():
dir_path = path.dirname(__file__) if "__file__" in locals() else os.getcwd()
#獲取停用詞的路徑
stopwords_path = os.path.join(dir_path,"txt/stopwords.txt")
#創(chuàng)建set集合來保存停用詞
stopwords = set()
#讀取文件
f = open(stopwords_path,"r",encoding="utf-8")
line_contents = f.readline()
while line_contents:
#去掉回車
line_contents = line_contents.replace("\n","").replace("\t","").replace("\u3000","")
stopwords.add(line_contents)
line_contents = f.readline()
return stopwords
c、生成詞云圖片
def drow_mask_wordColud():
#獲取當(dāng)前文件的父目錄
d = path.dirname(__file__) if "__file__" in locals() else os.getcwd()
mask = np.array(Image.open(path.join(d,"img/test.jpg")))
text = open(path.join(d,"txt/test.txt"),"r",encoding="utf-8").read().
replace("\n","").replace("\t","").replace("\u3000","")
#對(duì)文本進(jìn)行分詞
text = segment_words(text)
#獲取停用詞
stopwords = get_stopwords()
#創(chuàng)建詞云
'''
max_words:顯示詞的數(shù)量
mask:背景
stopwords:停用詞,是一個(gè)set集合
margin:詞之間的間隔
background_color:詞云圖片背景顏色
'''
wc = WordCloud(max_words=100,mask=mask,background_color="white",
stopwords=stopwords,margin=10,random_state=1).generate(text)
default_colors = wc.to_array()
# #保存詞云圖片
# wc.to_file("a_new_hope.png")
plt.imshow(default_colors,interpolation="bilinear")
plt.axis("off")
plt.show()

3、自定義詞云的顏色
from wordcloud import WordCloud,get_single_color_func
import matplotlib.pyplot as plt
'''
定義一個(gè)字體顏色設(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.defalt_color_func=get_single_color_func(default_color)
def get_color_func(self,word):
try:
#設(shè)置每個(gè)詞的顏色
color_func = next(color_func for (color_func,words) in self.color_func_to_words
if word in words)
except StopIteration:
#詞的默認(rèn)顏色
color_func = self.defalt_color_func
return color_func
def __call__(self,word,**kwargs):
return self.get_color_func(word)(word,**kwargs)
if __name__ == "__main__":
text = "第一 第二 第三 第四 第五 第六"
#創(chuàng)建詞云
wc = WordCloud(collocations=False,background_color="white").generate(text)
#設(shè)置詞的顏色
color_to_words={
#使用RGB來設(shè)置詞的顏色
"#00ff00":["第一","第五"],
"red":["第三","第六"],
"yellow":["第二"]
}
#設(shè)置詞默認(rèn)的顏色
default_color = "blue"
grouped_color_func = GroupedColorFunc(color_to_words,default_color)
#設(shè)置詞云的顏色
wc.recolor(color_func=grouped_color_func)
#顯示詞云圖
plt.figure()
plt.imshow(wc,interpolation="bilinear")
plt.axis("off")
plt.show()

通過詞的顏色設(shè)置類,來設(shè)置不同詞的顏色。
4、自定義突出詞的重要程度
在生成詞云的時(shí)候,默認(rèn)使用的是使得詞頻高的詞更加突出,突出的詞會(huì)比較大,有時(shí)候我們已經(jīng)計(jì)算出了詞的權(quán)重,想通過詞云圖來突出權(quán)重大小的差別。
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import numpy as np
def get_mask():
x,y = np.ogrid[:300,:300]
mask = (x-150) ** 2 + (y-150) ** 2 > 130 ** 2
mask = 255 * mask.astype(int)
return mask
if __name__ == "__main__":
#每個(gè)詞的權(quán)重
text = {"第一":0.1,"第二":0.2,"第三":0.3,"第四":0.4,"第五":0.5}
wc = WordCloud(background_color="white",mask=get_mask())
wc.generate_from_frequencies(text)
plt.axis("off")
plt.imshow(wc,interpolation="bilinear")
plt.show()

5、保存詞云圖片
wc.to_file("test.png")
更多關(guān)于python詞云庫wordCloud使用方法請(qǐng)查看下面的相關(guān)鏈接
相關(guān)文章
如何解決Python中tqdm和zip一起用進(jìn)度條不顯示問題
這篇文章主要介紹了如何解決Python中tqdm和zip一起用進(jìn)度條不顯示問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08
python實(shí)現(xiàn)學(xué)生成績(jī)測(cè)評(píng)系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)學(xué)生成績(jī)測(cè)評(píng)系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-06-06
python 不以科學(xué)計(jì)數(shù)法輸出的方法
今天小編就為大家分享一篇python 不以科學(xué)計(jì)數(shù)法輸出的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-07-07
基于Python詞云分析政府工作報(bào)告關(guān)鍵詞
這篇文章主要介紹了基于Python詞云分析政府工作報(bào)告關(guān)鍵詞,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06
Python技法之簡(jiǎn)單遞歸下降Parser的實(shí)現(xiàn)方法
遞歸下降解析器可以用來實(shí)現(xiàn)非常復(fù)雜的解析,下面這篇文章主要給大家介紹了關(guān)于Python技法之簡(jiǎn)單遞歸下降Parser的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-05-05
Python利用for循環(huán)打印星號(hào)三角形的案例
這篇文章主要介紹了Python利用for循環(huán)打印星號(hào)三角形的案例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-04-04
Python使用cn2an實(shí)現(xiàn)中文數(shù)字與阿拉伯?dāng)?shù)字的相互轉(zhuǎn)換
這篇文章主要介紹了Python使用cn2an實(shí)現(xiàn)中文數(shù)字與阿拉伯?dāng)?shù)字的相互轉(zhuǎn)換,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
使用Python 操作 xmind 繪制思維導(dǎo)圖的詳細(xì)方法
在平時(shí)的工作中當(dāng)我們要總結(jié)一些知識(shí)的時(shí)候就需要一款工具來畫畫流程圖,這里推薦 XMind 軟件,用 Xmind 繪制的思維導(dǎo)圖看起來思路清晰,那么今天的文章介紹關(guān)于思維導(dǎo)圖的相關(guān)知識(shí)以及用 Python 如何操作 Xmind 繪制思維導(dǎo)圖2021-10-10

