python - 为什么在使用 Python 的 wordcloud 库时,停用词没有从词云中排除?
问题描述
我想将“The”、“They”和“My”排除在我的词云中。我正在使用下面的 python 库“wordcloud”,并使用这 3 个额外的停用词更新 STOPWORDS 列表,但 wordcloud 仍然包括它们。我需要更改哪些内容才能排除这 3 个单词?
我导入的库是:
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
,因此云中包含两个相邻单词的频繁短语 - 重要的是,对于您的问题,搭配删除停用词是不同的,因此例如“谢谢”是一个有效的搭配,可能即使“你”在默认停用词中,也会出现在生成的云中。仅包含停用词的搭配将被删除。
这样做听起来不无道理的理由是,如果在构建搭配列表之前删除了停用词,那么例如“非常感谢”将提供“非常感谢”作为搭配,这是我绝对不想要的。
因此,为了让您的停用词按照您的预期工作,即云中根本没有停用词,您可以这样使用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 中的一个缺陷,不确定。然而,添加 egThe
到停用词不会影响这一点,因为停用词总是小写,无论搭配 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()
推荐阅读
- python - Python 对象检测代码,意外错误
- python - 提取最后的文本
标签
- pandas - 根据 pandas df 中的多个条件映射不同的数据帧
- google-chrome - Firefox / Chrome - WebRTC mediaDevices.enumerateDevices() - 不同的结果
- .net-core - .net core web api - 如何以块的形式返回表结果
- bitbucket - 如何在不更改内容的情况下触摸 bitbucket 中的文件
- excel - Razor-pages - 返回 FileContentResult 后文件未保存
- sql - 通过索引和/或 ID 有条件地加入表
- php - 检查时间是否已在 UTC 中重置
- r - 为什么我的 CalibrationCurve 功能部分工作?