使用spacy添加/删除停用词

问题描述 投票:27回答:4

使用spacy添加/删除停用词的最佳方法是什么?我正在使用token.is_stop函数,并希望对该集进行一些自定义更改。我正在查看文档,但找不到关于停用词的任何内容。谢谢!

python nlp stop-words spacy
4个回答
22
投票

您可以在处理文本之前编辑它们(请参阅this post):

>>> import spacy
>>> nlp = spacy.load("en")
>>> nlp.vocab["the"].is_stop = False
>>> nlp.vocab["definitelynotastopword"].is_stop = True
>>> sentence = nlp("the word is definitelynotastopword")
>>> sentence[0].is_stop
False
>>> sentence[3].is_stop
True

注意:这似乎有效<= v1.8。对于较新的版本,请参阅其他答案。


22
投票

使用Spacy 2.0.11,您可以使用以下方法之一更新其停用词集:

要添加单个停用词:

import spacy    
nlp = spacy.load("en")
nlp.Defaults.stop_words.add("my_new_stopword")

要一次添加几个停用词:

import spacy    
nlp = spacy.load("en")
nlp.Defaults.stop_words |= {"my_new_stopword1","my_new_stopword2",}

删除单个停用词:

import spacy    
nlp = spacy.load("en")
nlp.Defaults.stop_words.remove("whatever")

要一次删除几个停用词:

import spacy    
nlp = spacy.load("en")
nlp.Defaults.stop_words -= {"whatever", "whenever"}

注意:要查看当前的一组停用词,请使用:

print(nlp.Defaults.stop_words)

11
投票

对于2.0版,我使用了这个:

from spacy.lang.en.stop_words import STOP_WORDS

print(STOP_WORDS) # <- set of Spacy's default stop words

STOP_WORDS.add("your_additional_stop_word_here")

for word in STOP_WORDS:
    lexeme = nlp.vocab[word]
    lexeme.is_stop = True

这会将所有停用词加载到一个集合中。

您可以将停用词修改为STOP_WORDS或首先使用您自己的列表。


2
投票

对于2.0使用以下内容:

for word in nlp.Defaults.stop_words:
    lex = nlp.vocab[word]
    lex.is_stop = True
© www.soinside.com 2019 - 2024. All rights reserved.