1 概述
利用Python生成簡單的詞云,需要的工具是cython,wordcloud與anaconda.
2 準備工作
包括安裝cython,wordcloud與anaconda.
2.1 安裝anaconda
下載官網
選擇對應的版本下載即可.
2.2 安裝cython
cython是為了安裝wordcloud準備的.
1
|
pip - m pip install - - upgrade cython |
2.3 安裝wordcloud
安裝wordcloud前需要先安裝Microsoft Visuall C++ 14.0.
安裝好了以后重啟,輸入
1
|
python - m easy_install wordcloud |
3 使用
3.1 打開Jupyter
打開Jupyter Notebook.
然后會在瀏覽器打開這個頁面,新建一個notebook.
先把需要的庫導入:
1
2
|
from wordcloud import WordCloud import matplotlib.pyplot as plt |
3.2 創建文字庫
簡單的文字庫可以直接選擇一個txt文件,復雜的話可以選擇創建一個excel,導出為csv文件,然后利用pandas庫的read_csv()讀入文件.這里創建一個txt,空格分隔單詞即可.
然后上傳到Jupyter中:
3.3 生成詞云
首先讀入文件:
1
|
text = open ( '1.txt' ).read() |
然后使用WordCloud().generate(text),在里面設置各種屬性.
1
2
3
4
|
wc = WordCloud( width = 800 , repeat = True , height = 800 ).generate(text) |
這里設置了高度與寬度,允許重復.
1
2
3
|
plt.imshow(wc,interpolation = "bilinear" ) plt.axis( "off" ) plt.show() |
顯示詞云,
1
|
interpolation = 'bilinear' |
會使顯示平滑更加平滑,axis("off")表示不顯示坐標軸.
下面是效果:
3.4 注意事項
如果含有漢字,首先在讀取時設置編碼:
1
|
text = open ( '1.txt' ,encoding = 'utf-8' ) |
然后再生成詞云時設置字體:
1
|
wc = WordCloud(font_path = r 'C:\Windows\Fonts\simfang.ttf' ) |
測試:
1
2
3
4
5
6
7
8
9
|
text = open ( '1.txt' ,encoding = 'utf-8' ).read() wc = WordCloud( width = 1300 , repeat = True , font_path = r 'C:\Windows\Fonts\simfang.ttf' , height = 1300 ).generate(text) plt.imshow(wc,interpolation = "bilinear" ) plt.axis( "off" ) plt.savefig( 'aaaa.jpg' ) |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://segmentfault.com/a/1190000021574005