用 spacy 对文档进行词形还原?

Lemmatize a doc with spacy?

我有一个 spaCy doc,我想对其进行词形还原。

例如:

import spacy
nlp = spacy.load('en_core_web_lg')

my_str = 'Python is the greatest language in the world'
doc = nlp(my_str)

如何将 doc 中的每个标记转换为其引理?

每个令牌都有许多属性,您可以遍历文档来访问它们。

例如:[token.lemma_ for token in doc]

如果你想重构你可以使用的句子:' '.join([token.lemma_ for token in doc])

有关令牌属性的完整列表,请参阅:https://spacy.io/api/token#attributes

如果您不需要管道的特定组件 – 例如,NER parser,你可以禁止加载它。这有时会产生很大的不同,提高加载速度

对于您的情况(使用 spaCy 对文档进行词形还原),您只需要 tagger 组件。

所以这是一个示例代码:

import spacy

# keeping only tagger component needed for lemmatization
nlp = spacy.load('en_core_web_lg',  disable=["parser", "ner"])

my_str = 'Python is the greatest language in the world'

doc = nlp(my_str)
words_lemmas_list = [token.lemma_ for token in doc]
print(words_lemmas_list)

输出:

['Python', 'be', 'the', 'great', 'language', 'in', 'the', 'world']

此答案涵盖了您的文本由多个句子组成的情况。

如果您想获得所有被词形化的标记的列表,请执行:

import spacy
nlp = spacy.load('en')
my_str = 'Python is the greatest language in the world. A python is an animal.'
doc = nlp(my_str)

words_lemmata_list = [token.lemma_ for token in doc]
print(words_lemmata_list)
# Output: 
# ['Python', 'be', 'the', 'great', 'language', 'in', 'the', 'world', '.', 
# 'a', 'python', 'be', 'an', 'animal', '.']

如果您想获得每个标记都被词形化的所有句子的列表,请执行:

sentences_lemmata_list = [sentence.lemma_ for sentence in doc.sents]
print(sentences_lemmata_list)
# Output:
# ['Python be the great language in the world .', 'a python be an animal .']