標籤: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 詞雲 【中/英】小白簡單入門教程