Python 数据可视化:WordCloud 词云的构建
WordCloud 官方文檔:https://amueller.github.io/word_cloud/index.html
WordCloud GitHub 地址:https://github.com/amueller/word_cloud
Python非常重要的一個(gè)可視化庫(kù),wordcloud詞云庫(kù)了解一下!:https://www.bilibili.com/video/av26266917
一個(gè)免費(fèi)的生成詞云(word cloud)的在線工具:https://segmentfault.com/a/1190000016827687
python詞云 wordcloud 入門(mén) :https://blog.csdn.net/tanzuozhev/article/details/50789226
Python第三方庫(kù)wordcloud(詞云)快速入門(mén)與進(jìn)階:https://blog.csdn.net/qq_34337272/article/details/79552929
?
詞云可視化:安裝模塊 wordcloud:?pip install wordcloud
?
- 什么是詞云
詞云又叫文字云,是對(duì)文本數(shù)據(jù)中出現(xiàn)頻率較高的“關(guān)鍵詞”在視覺(jué)上的突出呈現(xiàn),形成關(guān)鍵詞的渲染形成類(lèi)似云一樣的彩色圖片,從而一眼就可以領(lǐng)略文本數(shù)據(jù)的主要表達(dá)意思。
?
- 準(zhǔn)備工作:
python開(kāi)發(fā)環(huán)境、wordcloud、jieba、matplotlib、numpy 、PIL 等庫(kù)文件安裝好。
?
安裝完成以后 ( 命令行使用方式 )
? ? ? ? wordcloud_cli --text in.txt --imagefile out.png --mask in.png
? ? ? ? text 是詞云來(lái)源,mask 是背景框架 ,imagefile 輸出的文件
? ? ? ? wordcloud_cli --help 查看所有支持的命令參數(shù)
?
wordcloud生成詞云的原理簡(jiǎn)介?
? ? ? ? wordcloud生成詞云的原理其實(shí)并不復(fù)雜,大體分成5步(具體可自行查看源碼):
- 1.wordcloud制作詞云時(shí),首先要對(duì)對(duì)文本數(shù)據(jù)進(jìn)行分詞,使用process_text()方法,這一步的主要任務(wù)是去除停用詞?
- 2.第二步是計(jì)算每個(gè)詞在文本中出現(xiàn)的頻率,生成一個(gè)哈希表。詞頻用于確定一個(gè)詞的重要性?
- 3.根據(jù)詞頻的數(shù)值按比例生成一個(gè)圖片的布局,類(lèi)IntegralOccupancyMap 是該詞云的算法所在,是詞云的數(shù)據(jù)可視化方式的核心。生成詞的顏色、位置、方向等?
- 4.最后將詞按對(duì)應(yīng)的詞頻在詞云布局圖上生成圖片,核心方法是generate_from_frequencies,不論是generate()還是generate_from_text()都最終用到generate_from_frequencies?
- 完成詞云上各詞的著色,默認(rèn)是隨機(jī)著色?
- 5.詞語(yǔ)的各種增強(qiáng)功能大都可以通過(guò)wordcloud的構(gòu)造函數(shù)實(shí)現(xiàn),里面提供了22個(gè)參數(shù),還可以自行擴(kuò)展。
?
wordcloud.WordCloud? 類(lèi) 的 參數(shù) 說(shuō)明
class wordcloud.WordCloud(font_path=None, width=400, height=200, margin=2, ranks_only=None, prefer_horizontal=0.9,mask=None, scale=1, color_func=None, max_words=200, min_font_size=4, stopwords=None, random_state=None,background_color='black', max_font_size=None, font_step=1, mode='RGB', relative_scaling=0.5, regexp=None, collocations=True,colormap=None, normalize_plurals=True)
參數(shù)
? ? font_path : string ? ? ? ? //字體路徑,需要展現(xiàn)什么字體就把該字體路徑+后綴名寫(xiě)上,如:font_path = '黑體.ttf’如果不指定字體中文字的顯示不出來(lái)
? ? width : int (default=400) ?//輸出的畫(huà)布寬度,默認(rèn)為400像素
? ? height : int (default=200) //輸出的畫(huà)布高度,默認(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 取代。
? ? scale : float (default=1) ? ? ? //按照比例進(jìn)行放大畫(huà)布,如設(shè)置為1.5,則長(zhǎng)和寬都是原來(lái)畫(huà)布的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,則忽略該方法。
?
示例 :
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Author : # @File : test.py # @Software : PyCharm # @description : XXXimport jieba from os import path import matplotlib.pyplot as plt import numpy as np from PIL import Image from scipy.misc import imread from wordcloud import WordCloud, ImageColorGenerator, STOPWORDSdef test_1():"""不是用背景圖片:return:"""f = open("e:/shijing_guanju.txt", "r")t = f.read()f.close()ls = jieba.lcut(t)txt = " ".join(ls)w = WordCloud(width=1000, height=700,background_color="white",# font_path="MSYH.ttc" # 沒(méi)有設(shè)置字體可能出現(xiàn),詞云的結(jié)果均為方框。建議設(shè)置MSYH.ttc(微軟雅黑)font_path="simsun.ttc" # 設(shè)置微軟雅黑報(bào)錯(cuò),這里設(shè)置 宋體)w.generate(txt)w.to_file("e:/word_cloud_1.png") # 在程序當(dāng)前目錄,word_cloud_1.pngdef test_2():"""使用背景圖片:return:"""mask = imread("e:/china_map.jpg") # 設(shè)置背景圖片china_map.jpgexcludes = {}f = open("e:/shijing_guanju.txt", "r")t = f.read()f.close()ls = jieba.lcut(t)txt = " ".join(ls)w = WordCloud(width=550, height=500,background_color="white",font_path="simsun.ttc", # 沒(méi)有設(shè)置字體可能出現(xiàn),詞云的結(jié)果均為方框。建議設(shè)置MSYH.ttc(微軟雅黑)mask=mask)w.generate(txt)w.to_file("e:/word_cloud_2.png") # 在程序當(dāng)前目錄,word_cloud_1.pngdef test_3():# 讀入背景圖片abel_mask = np.array(Image.open("/home/djh/PycharmProjects/source/test.jpg"))# 讀取要生成詞云的文件text_from_file_with_apath = open('/home/djh/PycharmProjects/source/a.txt').read()# 通過(guò)jieba分詞進(jìn)行分詞并通過(guò)空格分隔word_list_after_jieba = jieba.cut(text_from_file_with_apath, cut_all=True)wl_space_split = " ".join(word_list_after_jieba)# my_word_cloud = WordCloud().generate(wl_space_split) 默認(rèn)構(gòu)造函數(shù)my_word_cloud = WordCloud(background_color='white', # 設(shè)置背景顏色mask=abel_mask, # 設(shè)置背景圖片max_words=200, # 設(shè)置最大現(xiàn)實(shí)的字?jǐn)?shù)stopwords=STOPWORDS, # 設(shè)置停用詞font_path='/home/djh/win_font/simkai.ttf', # 設(shè)置字體格式,如不設(shè)置顯示不了中文max_font_size=50, # 設(shè)置字體最大值random_state=30, # 設(shè)置有多少種隨機(jī)生成狀態(tài),即有多少種配色方案scale=.5).generate(wl_space_split)# 根據(jù)圖片生成詞云顏色image_colors = ImageColorGenerator(abel_mask)# my_word_cloud.recolor(color_func=image_colors)# 以下代碼顯示圖片plt.imshow(my_word_cloud)plt.axis("off")plt.show()def test_4():"""簡(jiǎn)易版:return:"""f = open(u'txt/AliceEN.txt', 'r').read()wordcloud = WordCloud(background_color="white", width=1000, height=860, margin=2).generate(f)# width,height,margin可以設(shè)置圖片屬性# 你可以通過(guò)font_path參數(shù)來(lái)設(shè)置字體集# background_color參數(shù)為設(shè)置背景顏色,默認(rèn)顏色為黑色plt.imshow(wordcloud)plt.axis("off")plt.show()wordcloud.to_file('test.png')# 保存圖片,但是在第三模塊的例子中 圖片大小將會(huì)按照 mask 保存def test_5():"""進(jìn)階版:return:"""d = path.dirname(__file__)# Read the whole text.text = open(path.join(d, 'alice.txt')).read()# read the mask / color image taken from# http://jirkavinse.deviantart.com/art/quot-Real-Life-quot-Alice-282261010alice_coloring = np.array(Image.open(path.join(d, "alice_color.png")))# 設(shè)置停用詞stopwords = set(STOPWORDS)stopwords.add("said")# 你可以通過(guò) mask 參數(shù) 來(lái)設(shè)置詞云形狀wc = WordCloud(background_color="white", max_words=2000, mask=alice_coloring,stopwords=stopwords, max_font_size=40, random_state=42)# generate word cloudwc.generate(text)# create coloring from imageimage_colors = ImageColorGenerator(alice_coloring)# show# 在只設(shè)置mask的情況下,你將會(huì)得到一個(gè)擁有圖片形狀的詞云plt.imshow(wc, interpolation="bilinear")plt.axis("off")plt.figure()# recolor wordcloud and show# we could also give color_func=image_colors directly in the constructor# 我們還可以直接在構(gòu)造函數(shù)中直接給顏色# 通過(guò)這種方式詞云將會(huì)按照給定的圖片顏色布局生成字體顏色策略plt.imshow(wc.recolor(color_func=image_colors), interpolation="bilinear")plt.axis("off")plt.figure()plt.imshow(alice_coloring, cmap=plt.cm.gray, interpolation="bilinear")plt.axis("off")plt.show()if __name__ == '__main__':test_1()# test_2()# test_3()# test_4()# test_5()pass?
?
?
總結(jié)
以上是生活随笔為你收集整理的Python 数据可视化:WordCloud 词云的构建的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: JS 逆向 --- 过无限debugge
- 下一篇: python3 中的 eval 函数