
前言
之前我們已經(jīng)學(xué)習(xí)了如何使用wordcloud制作英文和中文詞云,今天我們接著講解,在實(shí)際制作詞云中,有很多詞是沒有展示出的意義的,例如我,他等主語,那如何不顯示這些詞了,這就涉及到停用詞。

wordcloud自帶停用詞
wordcloud自帶一個(gè)停用詞表,是一個(gè)集合的數(shù)據(jù)類型。
from wordcloud import STOPWORDS
print(STOPWORDS)

如果我們需要添入一些其他的詞的話,也很簡(jiǎn)單,直接用add或者update方法即可(因?yàn)檫@是集合數(shù)據(jù))。
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庫(kù)制作中文詞云圖,必須要分詞,所以總結(jié)下來,中文中需要設(shè)置停用詞的話可以有三種方法。
- 在分詞前,將中文文本的停用詞先過濾掉。
- 分詞的時(shí)候,過濾掉停用詞。
- 在wordcloud中設(shè)置stopwords。
在這里我們只講解第三種方法,設(shè)置stopwords,我們需要先有一個(gè)中文停用詞表,在網(wǎng)上下載即可,然后將停用詞表清洗為集合數(shù)據(jù)格式。
首先我們讀取停用詞表的內(nèi)容,設(shè)置為集合數(shù)據(jù)結(jié)構(gòu)。
stopwords = set()
content = [line.strip() for line in open('hit_stopwords.txt','r').readlines()]
stopwords.update(content)
stopwords

接著,我們就對(duì)文本進(jìn)行分詞,制作詞云圖即可。
from matplotlib import pyplot as plt
from wordcloud import WordCloud
import jieba
text = '我叫羅攀,他叫關(guān)羽,我叫羅攀,他叫劉備'
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)

最后,如何美化詞云圖,我們下期再見~