1. 程式人生 > >python與自然語言處理(五):中文文字詞雲

python與自然語言處理(五):中文文字詞雲

之前一直想要做一個文字的視覺化:詞雲,然後在網上搜到的一些製作詞雲的工具,有些是線上的就沒有使用,今天偶然看到python提供的wordcloud庫,可以方便製作詞雲,中英文皆可,趕緊試試,做個筆記,方便以後回顧。

首先是要安裝wordcloud庫

我從網站上下載的wordcloud版本為倒數第三個:


如果跟我使用的環境一致,下載網頁進不去的,可以到這裡下載我使用的版本:點這裡

然後使用anaconda prompt安裝wordcloud:



測試,使用wordcloud官網提供的示例,但換成中文文字:

# -*- coding: utf-8 -*-
"""
Created on Mon Jun  5 09:04:16 2017

@author: Owner
"""

from os import path
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

from wordcloud import WordCloud, STOPWORDS

d = path.dirname(__file__)

# Read the whole text.
#我這裡載入的檔案是已經分詞好的,如果載入的檔案是沒有分詞的,還需要使用分詞工具先進行分詞  
text = open(path.join(d, 'ctest2.txt'),encoding='utf-8').read()

# read the mask image
# taken from
# http://www.stencilry.org/stencils/movies/alice%20in%20wonderland/255fk.jpg
alice_mask = np.array(Image.open(path.join(d, "alice_mask.png")))

stopwords = set(STOPWORDS)
stopwords.add("said")

wc = WordCloud(
	#設定字型,不指定就會出現亂碼,這個字型檔案需要下載 
	font_path="HYQiHei-25JF.ttf",
	background_color="white", 
	max_words=2000, 
	mask=alice_mask,
	stopwords=stopwords)
	
# generate word cloud
wc.generate(text)

# store to file
wc.to_file(path.join(d, "alice_cloud.png"))

# show
plt.imshow(wc, interpolation='bilinear')
plt.axis("off")
plt.figure()
plt.imshow(alice_mask, cmap=plt.cm.gray, interpolation='bilinear')
plt.axis("off")
plt.show()


使用的模板圖 alice_mask.png 就是從 詞雲形狀素材 網站上下載的

執行程式:


左邊是模板圖,右邊是根據文字生成的詞雲圖,感覺很酷有沒有~~

如果在執行時報錯:OSError: cannotopen resource,一般是沒有支援的字型檔案,下載一個就可以了。

我使用的字型是  HYQiHei-25JF.ttf,可點這裡下載。