Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

11.2 停用词去除

有时,我们会排除那些提供很少价值的极其常见的单词,这些单词被称为停用词(Stop Words)。使用 NLTK 库去除停用词的代码如下所示:

text = "S&P and NASDAQ are the two most popular indices in US"
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
stop_words = set(stopwords.words('english'))
text_tokens = word_tokenize(text)
tokens_without_sw= [word for word in text_tokens if not word in stop_words]
print(tokens_without_sw)
['S', '&', 'P', 'NASDAQ', 'two', 'popular', 'indices', 'US']

我们首先加载语言模型,并将其存储在停用词变量中。stopwords.words(‘english’) 是 NLTK 中英语语言模型的默认停用词集合。

接下来,我们简单地迭代输入文本中的每个单词,如果该单词存在于 NLTK 语言模型的停用词集合中,则将其移除。正如我们所看到的,像 areinmost 这样的停用词已从句子中移除。