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

其中矩形框出來(lái)的是wordColud默認(rèn)的字體,橢圓形框的是我們下載的字體。
b、修改wordcolud.py文件中的字體設(shè)置,打開(kāi)改路徑下的wordcolud.py文件,找到下圖的所示的框出來(lái)的這一行(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
#用來(lái)正常顯示中文
plt.rcParams["font.sans-serif"]=["SimHei"]
#用來(lái)正常顯示負(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ì)詞云

下面以蠟筆小新的這張圖片作為背景來(lái)設(shè)計(jì)一個(gè)詞云,我們通過(guò)讀取一個(gè)txt文件,文件中包含了很多段落,然后通過(guò)jieba對(duì)句子進(jìn)行分詞,去除停用詞之后,生成一張?jiān)~云的照片。
a、讀取文件內(nèi)容
使用jieba分詞后,詞之間需要通過(guò)空格進(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:
#使用空格來(lái)分割詞
article_contents += word+" "
return article_contents
b、讀取停用詞
停用詞包括一些標(biāo)點(diǎn)符號(hào),和一些沒(méi)有實(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集合來(lái)保存停用詞
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來(lái)設(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()

通過(guò)詞的顏色設(shè)置類,來(lái)設(shè)置不同詞的顏色。
4、自定義突出詞的重要程度
在生成詞云的時(shí)候,默認(rèn)使用的是使得詞頻高的詞更加突出,突出的詞會(huì)比較大,有時(shí)候我們已經(jīng)計(jì)算出了詞的權(quán)重,想通過(guò)詞云圖來(lái)突出權(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詞云庫(kù)wordCloud使用方法請(qǐng)查看下面的相關(guān)鏈接
相關(guān)文章
windows上安裝python3教程以及環(huán)境變量配置詳解
這篇文章主要介紹了windows上安裝python3教程以及環(huán)境變量配置詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-07-07
打包Python代碼的常用方法實(shí)現(xiàn)程序exe應(yīng)用
Python是一門強(qiáng)大的編程語(yǔ)言,但在將Python代碼分享給其他人時(shí),讓他們安裝Python解釋器并運(yùn)行腳本可能有點(diǎn)繁瑣,這時(shí),將Python代碼打包成可執(zhí)行的應(yīng)用程序(.exe)可以大大簡(jiǎn)化這個(gè)過(guò)程,本文將介紹幾種常用的方法,輕松地將Python代碼變成獨(dú)立的可執(zhí)行文件2023-12-12
關(guān)于jupyter lab安裝及導(dǎo)入tensorflow找不到模塊的問(wèn)題
這篇文章主要介紹了關(guān)于jupyter lab安裝及導(dǎo)入tensorflow找不到模塊的問(wèn)題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-03-03
python實(shí)現(xiàn)按關(guān)鍵字篩選日志文件
今天小編大家分享一篇python實(shí)現(xiàn)按關(guān)鍵字篩選日志文件方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-12-12
python多線程http下載實(shí)現(xiàn)示例
python多線程http下載實(shí)現(xiàn)示例,大家參考使用吧2013-12-12
Python 如何操作 SQLite 數(shù)據(jù)庫(kù)
這篇文章主要介紹了Python 如何操作 SQLite 數(shù)據(jù)庫(kù),幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以了解下2020-08-08
python在回調(diào)函數(shù)中獲取返回值的方法
今天小編就為大家分享一篇python在回調(diào)函數(shù)中獲取返回值的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-02-02

