你好,我需要在使用spaCy时得到帮助。我试图做的是从我输入的句子中提取特定的名词。看看这里的少量代码,假设我想使用句子“the cat is better than a dog and a wolf”。我希望只提取第一个和第三个名词,并将它们分别赋值给随机变量。我该怎么做呢?目前的代码只是打印句子中的所有名词。谢谢你。
import spacy
frase1 = input('> \n\n')
nlp = spacy.load('en')
for t in nlp(frase1):
if t.tag_ in ['NN']:
print(t.text)
回答:
如果你想根据名词在句子中的位置获取名词(在你的例子中,是第一个和第三个),你可以这样做:
import spacy
import operator
nlp = spacy.load("en")
doc = nlp("The cat is better than a dog and a wolf.")
nns = [i.text for i in doc if i.tag_ == "NN"]
first, third = list(operator.itemgetter(0, 2)(nns))
如果你只想知道名词的总数,你可以这样做:
len(nns)