詞云百度百科:“詞云”就是對網(wǎng)絡(luò)文本中出現(xiàn)頻率較高的“關(guān)鍵詞”予以視覺上的突出,形成“關(guān)鍵詞云層”或“關(guān)鍵詞渲染”,,從而過濾掉大量的文本信息,,使瀏覽網(wǎng)頁者只要一眼掃過文本就可以領(lǐng)略文本的主旨 先上幾張圖片讓大家欣賞一番: 這是我之前爬取的一篇文章并進行可視化而形成的詞云 個性化——添加了個背景圖 一般情況下對本狗來講,, 更喜歡詞云。 廢話少說,, 開始教程: import jieba import numpy as np from PIL import Image from wordcloud import WordCloud from matplotlib import pyplot as plt 首先需要進行分詞,,也就是將一個句子分割成一個個的詞語,我這里使用的是jieba分詞
分好詞后就需要將詞做成詞云了,,我使用的是wordcloud from matplotlib import pyplot as plt from wordcloud import WordCloud string = ''' I volunteer to join the Communist Party of China, support the Party's program, abide by the Party's Articles of Association, fulfill Party duties, implement Party decisions, strictly observe Party discipline, keep the secrets of the Conservative Party, be loyal to the Party, work actively, and fight for communism for life. We are always ready to sacrifice everything for the Party and the people and never defect to the Party. ''' font = r'C:\Windows\Fonts\simfang.ttf' #設(shè)置字體路徑 wc = WordCloud(font_path=font, #如果是中文必須要添加這個,,否則會顯示成框框 background_color='white', width=1000, height=800, ).generate(string) wc.to_file('789.png') #保存圖片 plt.imshow(wc) #用plt顯示圖片 plt.axis('off') #不顯示坐標(biāo)軸 plt.show() #顯示圖片 效果圖:
通過添加 “mask=”這個屬性,, 來實現(xiàn)改變背景形狀,,但是 背景圖片必須是白底,它會在你非白底的地方填充上文字,, 所以最終我的代碼是這樣的: import jieba from matplotlib import pyplot as plt from wordcloud import WordCloud from PIL import Image import numpy as np path = r'文件存儲的目錄' font = r'C:\Windows\Fonts\FZSTK.TTF' text = (open(path+r',??,?,?.txt','r',encoding='utf-8')).read() cut = jieba.cut(text) #分詞 string = ' '.join(cut) print(len(string)) img = Image.open(path+r'\456.png') #打開背景圖 img_array = np.array(img) #將圖片裝換為數(shù)組 stopword=['xa0'] #設(shè)置停止詞,也就是你不想顯示的詞,,這里這個詞是我前期處理沒處理好,,你可以刪掉他看看他的作用 wc = WordCloud( background_color='white', width=1000, height=800, mask=img_array, font_path=font, stopwords=stopword ) wc.generate_from_text(string)#繪制圖片 plt.imshow(wc) plt.axis('off') plt.figure() plt.show() #顯示圖片 wc.to_file(path+r'\123.png') #保存圖片 圖片源: 效果圖: Python知識大全 |
|