用python產生詞雲

來源:互聯網
上載者:User

本文實現用Python產生任意圖形的文字雲圖

使用到的模組
文字雲需要用到兩個模組,分別是:jieba 和 wordcloud,可以通過pip方式進行安裝:

pip install jieba/wordcloud

在安裝wordcloud時,可能會遇到報錯:

這種情況可以換種方式進行安裝,在http://www.lfd.uci.edu/~gohlke/pythonlibs/#wordcloud 下方找到wordcloud的下載連結,下載對應的whl檔案,下載後進入儲存該檔案的路徑,執行“pip install wordcloud‑1.3.2‑cp35‑cp35m‑win_amd64.whl”就OK了。

思路
先使用jieba分詞對文章進行分詞,同時讀取背景的圖片(用於繪製不同形狀的文字圖雲),然後通過WordCloud產生文字圖雲並用畫圖工具進行展示。

樣本
將”紳士”歌詞製作成心形詞雲進行展示

實現代碼

#分詞模組import jieba#畫圖模組import matplotlib.pyplot as plt#文字雲模組from wordcloud import WordCloud#讀取背景圖片from scipy.misc import imread#檔案名稱word_file='word.txt'#讀取檔案內容word_content=open(word_file,'r',encoding='utf-8').read().replace('\n','')#設定背景圖片img_file='heart.jpg'#讀取背景圖片mask_img=imread(img_file)#進行分詞word_cut=jieba.cut(word_content)#把分詞用空格連起來word_cut_join=" ".join(word_cut)#產生詞雲wc=WordCloud(             font_path='msyh.ttf',#設定字型             max_words=50,#詞雲顯示的最大詞數             mask=mask_img,#設定背景圖片             background_color='white'#背景顏色             ).generate(word_cut_join)plt.imshow(wc)#去掉座標軸plt.axis('off')#將圖片儲存到本地plt.savefig('heart_cy.jpg')plt.show()

產生結果

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.