Python自然語言處理(三):Word Cloud文字雲

Yanwei Liu
3 min readJan 9, 2020

參考資料:

斷詞與文字雲教學 吳智鴻教授. 國立臺中教育大學數位內容科技學系

線上版文字雲

https://wordcloud.timdream.org/#wikipedia:Cloud

安裝

pip install wordcloud 
pip install jieba

下載資料檔案

#字典檔案
wget https://raw.githubusercontent.com/victorgau/wordcloud/master/dict.txt.big
#中文字體
wget https://raw.githubusercontent.com/victorgau/wordcloud/master/SourceHanSansTW-Regular.otf

程式

%matplotlib inline
import matplotlib.pyplot as plt
from wordcloud import WordCloud
from PIL import Image
import jieba
import numpy as np
# 如果檔案內有一些編碼錯誤,使用 errors='ignore' 來忽略錯誤
with open("107.csv", encoding="big5", errors='ignore') as f:
text = f.read()

# 設定使用 big5 斷詞
jieba.set_dictionary('dict.txt.big')
wordlist = jieba.cut(text)
words = " ".join(wordlist)
#文字雲造型圖片
mask = np.array(Image.open('picture.png')) #文字雲形狀
# 從 Google 下載的中文字型
font = 'SourceHanSansTW-Regular.otf'
#背景顏色預設黑色,改為白色、使用指定圖形、使用指定字體
my_wordcloud = WordCloud(background_color='white',mask=mask,font_path=font).generate(words)

plt.imshow(my_wordcloud)
plt.axis("off")
plt.show()
#存檔
wordcloud.to_file('word_cloud.png')

--

--