gpt4 book ai didi

python - 如何使用 spacy 对 python 中的列表列表进行词形还原?

转载 作者:太空宇宙 更新时间:2023-11-04 11:22:25 24 4
gpt4 key购买 nike

我有一个列表列表,其中包含需要进行词形还原的单词。我收到一条错误消息,指出需要字符串而不是列表,因为我使用的是 Spacy。

如果我转换为字符串,即 nlp(str(list_1)),则列表分隔符(如:“,”和“[”)被标记化并包含在我的输出中。

如何对列表列表中的项目进行词形还原并将其恢复为相同的形式,即列表列表?

需要词形还原的词可以在列表列表中的任何位置。

我想要这样的东西:

输入:

[["flower", "grows", "garden"], [["boy", "running", "playground"]]

输出:

[["flower", "grow", "garden"], ["boy", "run", "playground"]]

import spacy
nlp = spacy.load("en_core_web_sm")
list_1 = [["flower", "grows", "garden"], ["boy", "running", "playground"]]

for item in nlp(str(list_1)):
print(item.lemma_)

最佳答案

我会将这个任务分成以下几个部分:

1。创建 nlp 对象和你的文本

你已经做到了,但为了后代:

nlp = spacy.load("en_core_web_sm")
words = [["flower", "grows", "garden"], ["boy", "running", "playground"]]

2。获取每个列表的长度

我们需要知道每个列表的长度,以便稍后对其进行迭代(以 reshape 输出)。使用numpy.cumsum我们可以创建一个数组,它允许我们在 O(n) 时间内完成。

# remember about importing numpy
lengths = np.cumsum([0] + list(map(len, words)))
print(lengths)

这将为我们提供以下数组(针对您的情况):

[0 3 6]

稍后我们将使用从这个数组创建的范围,例如tokens [0:3] 构成第一个数组,tokens [3:6] 构成第二个数组。

3。展平你的数组并创建 Doc

flat_words = [item for sublist in words for item in sublist]
doc = spacy.tokens.Doc(nlp.vocab, words=flat_words)

最好将 flat_words 作为列表传递,这样 spacy 就不必执行不必要的标记化操作。

4。遍历跨度

最后遍历 spacy.tokens.Span对象,覆盖它们的标记并将它们添加到列表中(当然是 lemmatized)。

lemmatized = []
# Iterate starting with 1
for index in range(1, len(lengths)):
# Slice doc as described in the first point, so [0:3] and [3:6]
span = doc[lengths[index - 1] : lengths[index]]
# Add lemmatized tokens as list to the outer list
lemmatized.append([token.lemma_ for token in span])

print(lemmatized) 的输出将如您所愿:

[['flower', 'grow', 'garden'], ['boy', 'run', 'playground']]

5。完整代码

为了让您更轻松,下面是完整的代码:

import numpy as np
import spacy

nlp = spacy.load("en_core_web_sm")
words = [["flower", "grows", "garden"], ["boy", "running", "playground"]]

lengths = np.cumsum([0] + list(map(len, words)))
print(lengths)


flat_words = [item for sublist in words for item in sublist]
doc = spacy.tokens.Doc(nlp.vocab, words=flat_words)

lemmatized = []
# Iterate starting with 1
for index in range(1, len(lengths)):
# Slice doc as described in the first point, so [0:3] and [3:6]
span = doc[lengths[index - 1] : lengths[index]]
# Add lemmatized tokens as list to the list
lemmatized.append([token.lemma_ for token in span])

print(lemmatized)

关于python - 如何使用 spacy 对 python 中的列表列表进行词形还原?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55675788/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com