Python 詞雲 【中/英】小白簡單入門教程


1. 分析

構建詞雲需要具備:

  • 原料即文章等內容
  • 將內容進行分詞
  • 將分詞后的內容利用構建詞雲的工具進行構建
  • 保存成圖片

2. 需要的主要模塊

  • jieba 中文分詞
  • wordcloud 構建詞雲

3. 模塊原理

wordcloud的實現原理

  • 文本預處理
  • 詞頻統計 
  • 將高頻詞以圖片形式進行彩色渲染

jieba的實現原理

  • 進行中文分詞(有多種模式)【詳情

4. 英文詞雲

英文分詞和構建詞雲只需要wordcloud模塊

具體實現如下:

 1 from wordcloud import WordCloud
 2  
 3 string = 'Importance of relative word frequencies for font-size. With relative_scaling=0, only word-ranks are considered. With relative_scaling=1, a word that is twice as frequent will have twice the size. If you want to consider the word frequencies and not only their rank, relative_scaling around .5 often looks good.'
 4 font = r'C:\Windows\Fonts\FZSTK.TTF'
 5 wc = WordCloud(font_path=font, #如果是中文必須要添加這個,否則會顯示成框框
 6                background_color='white',
 7                width=1000,
 8                height=800,
 9                ).generate(string)
10 wc.to_file('ss.png') #保存圖片

5. 中文分詞

具體實現如下:

1 import jieba 
2 cut = jieba.cut(text)  #text為你需要分詞的字符串/句子
3 string = ' '.join(cut)  #將分開的詞用空格連接

6. 中文詞雲

中文詞雲需要jieba和wordcloud模塊

具體實現如下:

 1 import jieba
 2 from wordcloud import WordCloud
 3 from PIL import Image
 4 import numpy as np
 5 
 6 font = 'hwkt.ttf'
 7 content = (open('崗位需求.txt','r',encoding='utf-8')).read()
 8 cut = jieba.cut(content)
 9 cut_content = ' '.join(cut)
10 img = Image.open('22.png') # 以什么圖片進行顯示
11 img_array = np.array(img) # 將圖片轉換為數組
12 
13 wc = WordCloud(
14     background_color='white',
15     mask=img_array, # 若沒有該項,則生成默認圖片
16     font_path=font # 中文分詞必須有中文字體設置
17 )
18 wc.generate_from_text(cut_content) # 繪制圖片
19 wc.to_file('new.png') # 保存圖片

7. 實現效果

英文詞雲實現效果如下:

 

中文詞雲實現效果如下:

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM