词云(WordCloud)
生活随笔
收集整理的這篇文章主要介紹了
词云(WordCloud)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
WordCloud的參數(shù):
font_path:可用于指定字體路徑
width:詞云的寬度,默認(rèn)為 400;
height:詞云的?度,默認(rèn)為 200;
mask:蒙版,可?于定制詞云的形狀;
min_font_size:最?字號,默認(rèn)為 4;
max_font_size:最?字號,默認(rèn)為詞云的?度;
max_words:詞的最?數(shù)量,默認(rèn)為 200;
stopwords:將被忽略的停?詞,若不指定則使?默認(rèn)停?詞詞庫;
background_color:背景顏?,默認(rèn)為 black;
mode:默認(rèn)為RGB模式,如果為RGBA模式且background_color設(shè) 為 None,則背景將透明。
generate(str) 接受一個字符串
生成一個詞云只需要:
wc = WordCloud().generate(text)
plt.imshow(wc, interpolation='bilinear')
# 打開文本
text = open(base_dir + 'constitution.txt').read()
# 生成對象
wc = WordCloud().generate(text)
# 顯示
plt.imshow(wc, interpolation='bilinear')
plt.axis('off')
plt.show()
wc.to_file("默認(rèn)樣式.png")
自定義字體
wc = WordCloud('Hiragino.ttf')
使用中文
# 分詞
text_new = " ".join(jieba.cut(text))
wc = WordCloud('Hiragino.ttf') # 不加字體會中文亂碼
使用蒙版,
透明背景: mode='RGBA', background_color=None
mask = np.array(Image.open("black_mask.png"))
wc = WordCloud(font_path='Hiragino.ttf', mode='RGBA', background_color=None, mask=mask, width=600, height=400)
使用圖片(蒙版)中的顏色
image_colors = ImageColorGenerator(mask)
wc.recolor(color_func=image_colors)
自定義顏色函數(shù)
# 顏色函數(shù)
def random_color(word, font_size, position, orientation, font_path, random_state):
s = 'hsl(0, %d%%, %d%%)' % (random.randint(60, 80), random.randint(60, 80))
return s
...
wc = WordCloud(color_func=random_color, font_path='Hiragino.ttf',mode='RGBA', background_color=None, mask=mask)
使用權(quán)重
# 提取關(guān)鍵詞和權(quán)重
freq = jieba.analyse.extract_tags(text_new, topK=200, withWeight=True) # 列表
freq = {i[0]: i[1] for i in freq} # 字典
mask = np.array(Image.open(f"{base_dir}color_mask.png"))
wc = WordCloud(font_path='Hiragino.ttf',mode='RGBA', background_color=None, mask=mask)
res = wc.generate_from_frequencies(freq)
也可以使用:
freq = nltk.FreqDist(word_text)
# wc.fit_words(freq) # 然后再generate
wc.generate_from_frequencies(freq)
輸出
提供了四個輸出函數(shù):
to_array(self):numpy數(shù)組格式
to_file(self, filename)
to_html(self):沒有實現(xiàn)
to_image(self):PIL圖像
依賴的包如下:
from wordcloud import WordCloud
from wordcloud import ImageColorGenerator
import matplotlib.pyplot as plt
import jieba
import jieba.analyse
from PIL import Image
import random
import numpy as np
總結(jié)
以上是生活随笔為你收集整理的词云(WordCloud)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 路由器怎么连接互联网路由器网站如何连接
- 下一篇: 认识自己的无线路由器如何识别无线路由器