Python基于WordCloud制作詞云圖
這篇文章主要介紹了python基于WordCloud制作詞云圖,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
1. 導(dǎo)入需要的包package
import matplotlib.pyplot as plt from scipy.misc import imread from wordcloud import WordCloud,STOPWORDS import xlrd
2. 設(shè)置生成詞云圖的背景圖片,最好是分辨率高且色彩邊界分明的圖片
def set_background(picpath): back_coloring = imread(picpath)# 設(shè)置背景圖片,png等圖片格式 return back_coloring
3. 創(chuàng)建詞云圖:WordCloud
def create_word_cloud(txt_str, back_coloring): #txt_str表示導(dǎo)入的是字符串格式數(shù)據(jù),#back_color表示的是背景圖片位置
print('---- 根據(jù)詞頻,開(kāi)始生成詞云! ----')
font = r'C:\Windows\Fonts\simsun.ttc' #加載顯示字體
wc = WordCloud(
font_path=font,
collocations=False, # 去重,如果不加,詞云圖會(huì)顯示相同的詞
stopwords=STOPWORDS, #加載停用詞,如果不自己指定,則會(huì)加載默認(rèn)的停用詞
max_words=100,
width=2000,
height=1200,
# background_color='white',
mask=back_coloring,
)
wordcloud = wc.generate(txt_str)
# 寫(xiě)詞云圖片
wordcloud.to_file(".\wordcloud_test.png")
# 顯示詞云文件
plt.imshow(wordcloud)
plt.axis("off")
plt.show()
4. 默認(rèn)的停用詞一般在:假如anaconda安裝在D盤(pán),則會(huì)在其目錄:D:\Anaconda3\Lib\site-packages\wordcloud\stopwords,其中都是英文詞,例如:


注意:也可以在jieba分詞中,先利用自己的停用詞,得到去除停用詞之后的文本字符串來(lái)繪制詞云圖:
5. 此時(shí),詞云圖無(wú)法顯示數(shù)字,這是因?yàn)?wc.generate 操作中,有去除數(shù)字的語(yǔ)句:在wordcloud.py中,第560行左右,所以想要顯示數(shù)字,需要先注釋這一行

6. 假設(shè)想要顯示的詞,已經(jīng)經(jīng)過(guò)jieba分詞,保存在txt文檔中,則繪制詞云圖的方法是:
例如:txt中是每行是一個(gè)詞:

則,先讀取txt文件,形成字符串格式文本,再繪制
if __name__ == '__main__':
picpath = r".\xxx.png" #背景圖片路徑
back_coloring = set_background(picpath)
with open(r".\jieba_分詞數(shù)據(jù).txt", "r",encoding='utf-8') as f:
remove_stop_str = f.read()
create_word_cloud(remove_stop_str, back_coloring)
7. 如果通過(guò)jieba分詞的數(shù)據(jù)已經(jīng)處理成了(詞, 詞頻)并保存在excel中,例如這種兩列格式的excel表,第一行是標(biāo)簽如(詞, 詞頻):

則可以先讀取詞頻再顯示,python讀取excel數(shù)據(jù)可以通過(guò) xlrd.open_workbook 方法:
def read_from_xls(filepath,index_sheet):
#讀取文件名,filepath是excel文件的路徑,index_sheet是第幾個(gè)sheet
#讀取表格#
# 設(shè)置GBK編碼
xlrd.Book.encoding = "gbk"
rb = xlrd.open_workbook(filepath)
print(rb)
sheet = rb.sheet_by_index(index_sheet)
nrows = sheet.nrows
data_tmp = []
for i in range(nrows - 1):
tt=i+1 #excel的第一行是標(biāo)簽
tmp_char = [str(sheet.cell_value(tt,0))] #第一列是詞
tmp_num = int(sheet.cell_value(tt,1)) #第二列是詞頻
data_tmp.extend(tmp_char*tmp_num)
return data_tmp
然后,讀數(shù)據(jù)和生成詞云圖:
if __name__ == '__main__': picpath = r".\xxx.png" back_coloring = set_background(picpath) data_dic = read_from_xls(r'D:\Python_workspace\spyder_space\jieba分詞表.xlsx',0) data_dic_str = '\n'.join(data_dic) #轉(zhuǎn)成字符串格式 create_word_cloud(data_dic_str, back_coloring)
8. 總結(jié)代碼
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 19 10:47:17 2019
@author: Administrator
"""
import matplotlib.pyplot as plt
from scipy.misc import imread
from wordcloud import WordCloud,STOPWORDS
import xlrd
def set_background(picpath):
back_coloring = imread(picpath)# 設(shè)置背景圖片
return back_coloring
def create_word_cloud(txt_str, back_coloring):
print('---- 根據(jù)詞頻,開(kāi)始生成詞云! ----')
font = r'C:\Windows\Fonts\simsun.ttc'
wc = WordCloud(
font_path=font,
collocations=False, # 去重
stopwords=STOPWORDS,
max_words=100,
width=2000,
height=1200,
# background_color='white',
mask=back_coloring,
)
wordcloud = wc.generate(txt_str)
# 寫(xiě)詞云圖片
wordcloud.to_file(".\wordcloud_test.png")
# 顯示詞云文件
plt.imshow(wordcloud)
plt.axis("off")
plt.show()
def read_from_xls(filepath,index_sheet):
#讀取文件名
#讀取表格#
# 設(shè)置GBK編碼
xlrd.Book.encoding = "gbk"
rb = xlrd.open_workbook(filepath)
print(rb)
sheet = rb.sheet_by_index(index_sheet)
nrows = sheet.nrows
data_tmp = []
for i in range(nrows - 1):
tt=i+1
tmp_char = [str(sheet.cell_value(tt,0))]
tmp_num = int(sheet.cell_value(tt,1))
data_tmp.extend(tmp_char*tmp_num)
return data_tmp
if __name__ == '__main__':
picpath = r".\xxx.png"
back_coloring = set_background(picpath)
data_dic = read_from_xls(r'D:\Python_workspace\spyder_space\jieba分詞表.xlsx',0)
data_dic_str = '\n'.join(data_dic)
# with open(r".\jieba_分詞數(shù)據(jù).txt", "r",encoding='utf-8') as f:
# remove_stop_str = f.read()
create_word_cloud(data_dic_str, back_coloring)
當(dāng)然繪制詞云圖的方法有很多,這只是其中的一種
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python matplotlib畫(huà)盒圖、子圖解決坐標(biāo)軸標(biāo)簽重疊的問(wèn)題
今天小編就為大家分享一篇python matplotlib畫(huà)盒圖、子圖解決坐標(biāo)軸標(biāo)簽重疊的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-01-01
Python編程根據(jù)字典列表相同鍵的值進(jìn)行合并
這篇文章主要介紹了來(lái)學(xué)習(xí)Python字典列表根據(jù)相同鍵的值進(jìn)行合并的操作方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-10-10
Python流行ORM框架sqlalchemy的簡(jiǎn)單使用
這篇文章主要介紹了Python流行ORM框架sqlalchemy的簡(jiǎn)單使用,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-07-07
Python如何實(shí)現(xiàn)macOS系統(tǒng)代理的設(shè)置
這篇文章主要為大家詳細(xì)介紹了Python如何實(shí)現(xiàn)macOS系統(tǒng)代理的設(shè)置,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-01-01
python實(shí)現(xiàn)自動(dòng)化腳本編寫(xiě)
自動(dòng)化在很多時(shí)候是很方便的,本文以修改用戶名密碼單元為案例,編寫(xiě)測(cè)試腳本。完成修改用戶名密碼模塊單元測(cè)試,感興趣的可以了解一下2021-06-06
pytorch中with?torch.no_grad():的用法實(shí)例
最近在看別人寫(xiě)的代碼,遇到經(jīng)常使用with torch.no_grad(),所以下面這篇文章主要給大家介紹了關(guān)于pytorch中with?torch.no_grad():用法的相關(guān)資料,需要的朋友可以參考下2022-03-03

