使用Python的wordcloud库时,为什么不将停用词排除在词云之外?
我想将“ The”,“他们”和“
My”排除在我的词云中。我正在使用如下所示的python库’wordcloud’,并使用这3个其他停用词来更新STOPWORDS列表,但wordcloud仍包括它们。我需要更改什么才能排除这三个词?
我导入的库是:
import numpy as np
import pandas as pd
from wordcloud import WordCloud, STOPWORDS
import matplotlib.pyplot as plt
我曾尝试按照以下步骤将元素添加到STOPWORDS集中,但是即使单词添加成功,wordcloud仍显示我添加到STOPWORDS集中的3个单词:
len(STOPWORDS)
输出:192
然后我跑了:
STOPWORDS.add('The')
STOPWORDS.add('They')
STOPWORDS.add('My')
然后我跑了:
len(STOPWORDS)
输出:195
我正在运行python版本3.7.3
我知道我可以在运行wordcloud之前修改文本输入以删除3个单词(而不是尝试修改WordCloud的STOPWORDS集),但是我想知道WordCloud是否存在错误,或者我是否未正确更新/使用STOPWORDS?
-
Wordcloud的默认设置是
collocations=True
,因此两个相邻单词的常用短语都包含在云中-
对于您的问题,重要的是,搭配使用时,停用词的去除方式有所不同,例如“谢谢”是有效的搭配,并且可能即使默认单词中的“
you”也会出现在生成的云中。仅包含停用词的 并置会被 删除。听起来不合理的理由是,如果在构建搭配列表之前删除停用词,则例如“非常感谢”将提供“非常感谢”作为搭配,我当然不希望这样。
因此,为了使您的停用词按预期运行,即云中完全没有停用词出现,可以这样使用
collocations=False
:my_wordcloud = WordCloud( stopwords=my_stopwords, background_color='white', collocations=False, max_words=10).generate(all_tweets_as_one_string)
更新:
- 如果并置为False,则停用词都将全部小写,以便在删除时将其与小写文本进行比较-因此无需添加’The’等。
- 如果搭配词为True(默认),而停用词是小写的,则在寻找所有停用词搭配以将其删除时,源文本不是小写的,因此
The
删除时文本中的鸡蛋也不会the
被删除-这就是@Balaji Ambresh的原因代码有效,您将看到云中没有上限。不确定,这可能是Wordcloud中的缺陷。但是,The
在停用词中添加例如不会影响这一点,因为停用词总是小写,无论并置为True / False
这在源代码中都是可见的:-)
例如,使用默认值,
collocations=True
我得到:码:
from wordcloud import WordCloud from matplotlib import pyplot as plt text = "The bear sat with the cat. They were good friends. " + \ "My friend is a bit bear like. He's lovely. The bear, the cat, the dog and me were all sat " + \ "there enjoying the view. You should have seen it. The view was absolutely lovely. " + \ "It was such a lovely day. The bear was loving it too." cloud = WordCloud(collocations=False, background_color='white', max_words=10).generate(text) plt.imshow(cloud, interpolation='bilinear') plt.axis('off') plt.show()