各參數(shù)解釋(部分)
font_path : string #字體路徑磨总,需要展現(xiàn)什么字體就把該字體路徑+后綴名寫上哄啄,如:font_path = '黑體.ttf'
width : int (default=400) #輸出的畫布寬度粗截,默認(rèn)為400像素
height : int (default=200) #輸出的畫布高度墙牌,默認(rèn)為200像素
prefer_horizontal : float (default=0.90) #詞語(yǔ)水平方向排版出現(xiàn)的頻率很澄,默認(rèn) 0.9 (所以詞語(yǔ)垂直方向排版出現(xiàn)頻率為 0.1 )
mask : nd-array or None (default=None) #如果參數(shù)為空乳讥,則使用二維遮罩繪制詞云聪舒。如果 mask 非空昆雀,設(shè)置的寬高值將被忽略辱志,遮罩形狀被 mask 取代。除全白(#FFFFFF)的部分將不會(huì)繪制狞膘,其余部分會(huì)用于繪制詞云荸频。如:bg_pic = imread('讀取一張圖片.png'),背景圖片的畫布一定要設(shè)置為白色(#FFFFFF)客冈,然后顯示的形狀為不是白色的其他顏色旭从。可以用ps工具將自己要顯示的形狀復(fù)制到一個(gè)純白色的畫布上再保存场仲,就ok了和悦。
scale : float (default=1) #按照比例進(jìn)行放大畫布,如設(shè)置為1.5渠缕,則長(zhǎng)和寬都是原來(lái)畫布的1.5倍
min_font_size : int (default=4) #顯示的最小的字體大小
font_step : int (default=1) #字體步長(zhǎng)鸽素,如果步長(zhǎng)大于1,會(huì)加快運(yùn)算但是可能導(dǎo)致結(jié)果出現(xiàn)較大的誤差
max_words : number (default=200) #要顯示的詞的最大個(gè)數(shù)
stopwords : set of strings or None #設(shè)置需要屏蔽的詞亦鳞,如果為空馍忽,則使用內(nèi)置的STOPWORDS
background_color : color value (default=”black”) #背景顏色棒坏,如background_color='white',背景顏色為白色
max_font_size : int or None (default=None) #顯示的最大的字體大小
mode : string (default=”RGB”) #當(dāng)參數(shù)為“RGBA”并且background_color不為空時(shí),背景為透明
relative_scaling : float (default=.5) #詞頻和字體大小的關(guān)聯(lián)性
color_func : callable, default=None #生成新顏色的函數(shù)遭笋,如果為空坝冕,則使用 self.color_func
regexp : string or None (optional) #使用正則表達(dá)式分隔輸入的文本
collocations : bool, default=True #是否包括兩個(gè)詞的搭配
colormap : string or matplotlib colormap, default=”viridis” #給每個(gè)單詞隨機(jī)分配顏色,若指定color_func瓦呼,則忽略該方法
random_state : int or None #為每個(gè)單詞返回一個(gè)PIL顏色
fit_words(frequencies) #根據(jù)詞頻生成詞云
generate(text) #根據(jù)文本生成詞云
generate_from_frequencies(frequencies[, ...]) #根據(jù)詞頻生成詞云
generate_from_text(text) #根據(jù)文本生成詞云
process_text(text) #將長(zhǎng)文本分詞并去除屏蔽詞(此處指英語(yǔ)喂窟,中文分詞還是需要自己用別的庫(kù)先行實(shí)現(xiàn),使用上面的 fit_words(frequencies) )
recolor([random_state, color_func, colormap]) #對(duì)現(xiàn)有輸出重新著色央串。重新上色會(huì)比重新生成整個(gè)詞云快很多
to_array() #轉(zhuǎn)化為 numpy array
to_file(filename) #輸出到文件
具體實(shí)現(xiàn)
1.jpg
import numpy as np
import matplotlib.pyplot as plt
#pip install WordCloud
from wordcloud import WordCloud,STOPWORDS
from PIL import Image
from os import path
import cv2
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
#pip install jieba
import random,jieba
'''
繪制單個(gè)詞一個(gè)圓形的詞云(設(shè)置每個(gè)值的權(quán)重)
'''
def single_wordColud_1():
text = {"第一":0.1,"第二":0.2,"第三":0.3,"第四":0.4}
#產(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",font_path='./simkai.ttf',repeat=True,mask=mask)
wc.generate_from_frequencies(text)
#將x軸和y軸坐標(biāo)隱藏
plt.axis("off")
plt.imshow(wc,interpolation="bilinear")
plt.show()
'''
繪制單個(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",font_path='./simkai.ttf',repeat=True,mask=mask)
wc.generate(text)
#將x軸和y軸坐標(biāo)隱藏
plt.axis("off")
plt.imshow(wc,interpolation="bilinear")
plt.show()
def grey_color_func(word,font_size,position,orientation,random_state=None,**kwargs):
return "hsl(0,0%%,%d%%)"%random.randint(60,100)
'''
從文件中讀取停用詞
'''
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
'''
中文分詞
'''
def segment_words(text):
article_contents = ""
#使用jieba(結(jié)巴)進(jìn)行分詞
words = jieba.cut(text,cut_all=False)
for word in words:
#使用空格來(lái)分割詞
article_contents += word+" "
return article_contents
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")))
#以下用咱們剛剛另存為的圖就可以(必須是白色背景)
mask = cv2.imread("img/1.jpg")
#test.txt內(nèi)容隨便寫
text = open(path.join("txt/test.txt"),"r",encoding="utf-8").read().replace("\n","").replace("\t","").replace("\u3000","")
#text = "甜心 美麗 漂亮 性感 賢惠 溫柔 可愛(ài) 寶寶 排長(zhǎng)"
print(text)
#對(duì)文本進(jìn)行分詞
text = segment_words(text)
#獲取停用詞
stopwords = get_stopwords()
#創(chuàng)建詞云
'''
字體路徑 :simkai.ttf 簡(jiǎn)體字磨澡,解決漢字出現(xiàn)框框的問(wèn)題 這個(gè)文件只要你安裝了WordCloud第三方庫(kù)就有的了,如果不知道路徑质和,Everything直接搜索(簡(jiǎn)單粗暴)
scale:條件生成詞云的清晰度稳摄,值越大越清晰 默認(rèn)是1
max_words:顯示詞的數(shù)量
mask:背景
stopwords:停用詞,是一個(gè)set集合 有的話就自己定義就行了,或者用內(nèi)置的STOPWORDS stopwords=STOPWORDS 或者直接不設(shè)置
margin:詞之間的間隔
background_color:詞云圖片背景顏色
repeat:為詞是否可重復(fù) true 為可重復(fù) 默認(rèn)false 不可重復(fù)
'''
wc = WordCloud(scale=4,max_words=300,mask=mask,background_color="white",font_path='./simkai.ttf',stopwords=stopwords,margin=10,random_state=1).generate(text)
default_colors = wc.to_array()
# #保存詞云圖片(自定義)
wc.to_file("img/test.png")
plt.imshow(default_colors,interpolation="bilinear")
plt.axis("off")
plt.show()
if __name__ == "__main__":
drow_mask_wordColud()
#single_wordColud()
#single_wordColud_1()
結(jié)果
test.png
自定義一個(gè)字體顏色
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,font_path='./simkai.ttf',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()