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

來源:互聯網
上載者:User

標籤:content   tar   利用   tps   nump   text   教程   ice   font   

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. 實現效果

英文詞雲實現效果如下:

 

中文詞雲實現效果如下:

 

 

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.