向scikit-learn的CountVectorizer添加停用词

37 投票
1 回答
27308 浏览
提问于 2025-04-18 10:53

Scikit-learn中的CountVectorizer类允许你在参数stop_words中传入一个字符串'english',这样就可以使用预定义的英文停用词列表。我想在这个预定义的列表中添加一些词。有没有人能告诉我该怎么做?

1 个回答

67

根据 这个源代码,在 sklearn.feature_extraction.text 里,有一个完整的英文停用词列表(实际上是一个 frozenset,来自 stop_words),这个列表通过 __all__ 被公开了。所以如果你想用这个列表再加上一些其他的词,你可以这样做:

from sklearn.feature_extraction import text 

stop_words = text.ENGLISH_STOP_WORDS.union(my_additional_stop_words)

(这里的 my_additional_stop_words 可以是任何一串字符串)然后把结果作为 stop_words 参数使用。这个输入会被 CountVectorizer.__init__ 处理,处理的过程是通过 _check_stop_list,它会直接把新的 frozenset 传递过去。

撰写回答