后来,我使用这个spacy代码将它应用到我的文本中,但是我需要在文本中保留否定词,比如"not“。
nlp = spacy.load("en_core_web_sm")
def my_tokenizer(sentence):
return [token.lemma_ for token in tqdm(nlp(sentence.lower()), leave = False) if token.is_stop == False and token.is_alpha == True and token.lemma_ ] 当我申请的时候,我得到了这个结果:
[hello, earphone, work]然而,原来的句子是
hello,my earphones are still not working.所以,我想看看下面这句话:[earphone, still, not, work]谢谢
发布于 2022-08-02 13:10:12
"not“实际上是一个停止词,在您的代码中,如果一个令牌被删除,如果它是一个停止词。您可以通过查看Spacy停止词的列表来看到这一点。
"not" in spacy.lang.en.stop_words.STOP_WORDS或者循环遍历doc对象的令牌。
for tok in nlp(text.lower()):
print(tok.text, tok.is_stop, tok.lemma_)
#hello False hello
#, False ,
#my True my
#earphones False earphone
#are True be
#still True still
#not True not
#working False work
#. False .解决方案
要解决这个问题,您应该从stop_words列表中删除诸如"not“这样的目标单词。你可以这样做:
# spacy.lang.en.stop_words.STOP_WORDS.remove("not")
# or for multiple words use this
to_del_elements = {"not", "no"}
nlp.Defaults.stop_words = nlp.Defaults.stop_words - to_del_elements然后,您可以重新运行您的代码,您将得到您的预期结果:
import spacy
#spacy.lang.en.stop_words.STOP_WORDS.remove("not")
to_del_elements = {"not", "no"}
nlp.Defaults.stop_words = nlp.Defaults.stop_words - to_del_elements
nlp = spacy.load("en_core_web_sm")
def my_tokenizer(sentence):
return [token.lemma_ for token in tqdm(nlp(sentence.lower()), leave = False) if token.is_stop == False and token.is_alpha == True and token.lemma_ ]
sentence = "hello,my earphones are still not working. no way they will work"
results = my_tokenizer(sentence)
print(results)
#['hello', 'earphone', 'not', 'work', 'no', 'way', 'work']https://stackoverflow.com/questions/73205546
复制相似问题