前言
之前我們已經學習瞭如何使用wordcloud製作英文和中文詞雲,今天我們接着講解,在實際製作詞雲中,有很多詞是沒有展示出的意義的,例如我,他等主語,那如何不顯示這些詞了,這就涉及到停用詞。
wordcloud自帶停用詞
wordcloud自帶一個停用詞表,是一個集合的數據類型。
from wordcloud import STOPWORDS
print(STOPWORDS)
如果我們需要添入一些其他的詞的話,也很簡單,直接用add或者update方法即可(因爲這是集合數據)。
from matplotlib import pyplot as plt
from wordcloud import WordCloud,STOPWORDS
text = 'my is luopan. he is zhangshan'
stopwords = STOPWORDS
stopwords.add('luopan')
wc = WordCloud(stopwords=stopwords)
wc.generate(text)
plt.imshow(wc)
中文停用詞使用
用wordcloud庫製作中文詞雲圖,必須要分詞,所以總結下來,中文中需要設置停用詞的話可以有三種方法。
- 在分詞前,將中文文本的停用詞先過濾掉。
- 分詞的時候,過濾掉停用詞。
- 在wordcloud中設置stopwords。
在這裏我們只講解第三種方法,設置stopwords,我們需要先有一箇中文停用詞表,在網上下載即可,然後將停用詞表清洗爲集合數據格式。
首先我們讀取停用詞表的內容,設置爲集合數據結構。
stopwords = set()
content = [line.strip() for line in open('hit_stopwords.txt','r').readlines()]
stopwords.update(content)
stopwords
接着,我們就對文本進行分詞,製作詞雲圖即可。
from matplotlib import pyplot as plt
from wordcloud import WordCloud
import jieba
text = '我叫羅攀,他叫關羽,我叫羅攀,他叫劉備'
cut_word = " ".join(jieba.cut(text))
stopwords = set()
content = [line.strip() for line in open('hit_stopwords.txt','r').readlines()]
stopwords.update(content)
wc = WordCloud(font_path = r'/System/Library/Fonts/Supplemental/Songti.ttc',
stopwords = stopwords)
wc.generate(cut_word)
plt.imshow(wc)
最後,如何美化詞雲圖,我們下期再見~