从文本中删除停止词,同时不删除重复的常规词

2024-07-07 08:58:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个列表,其中包含特定文本文件中最常见的50个单词,但是我想从列表中删除停止词。我已经用这个代码做了。你知道吗

from nltk.corpus import gutenberg
carroll = nltk.Text(nltk.corpus.gutenberg.words('carroll-alice.txt'))
carroll_list = FreqDist(carroll)
stops = set(stopwords.words("english"))
filtered_words = [word for word in carroll_list if word not in stops]

然而,这是删除重复的话,我想要的。就像我这样做的时候:

fdist = FreqDist(filtered_words)
fdist.most_common(50)

我得到输出:

 [('right', 1), ('certain', 1), ('delighted', 1), ('adding', 1), 
 ('work', 1),      ('young', 1), ('Up', 1), ('soon', 1), ('use', 1),     
 ('submitted', 1), ('remedies', 1), ('tis', 1), ('uncomfortable', 1)....]

据说每个词都有一个实例,很明显它消除了重复。我想保留副本,这样我就能知道哪个词最常见。任何帮助都将不胜感激。你知道吗


Tags: in列表corpus单词filteredlistwordwords
1条回答
网友
1楼 · 发布于 2024-07-07 08:58:17

正如您现在所写的,list已经是一个包含单词作为键和出现计数作为值的分布:

>>> list
FreqDist({u',': 1993, u"'": 1731, u'the': 1527, u'and': 802, u'.': 764, u'to': 725, u'a': 615, u'I': 543, u'it': 527, u'she': 509, ...})

然后你在键上迭代意味着每个单词只存在一次。我相信你真的想创造这样的filtered_words

filtered_words = [word for word in carroll if word not in stops]

另外,应该尽量避免使用与Python内置函数匹配的变量名(list是Python内置函数)。你知道吗

相关问题 更多 >