【问题标题】:How can I fix the bug to realize reference resolution using a library?如何修复错误以使用库实现引用解析?
【发布时间】:2020-08-22 17:20:28
【问题描述】:

我想做的事

我想使用 Python 3.6 和 spaCy neuralcoref 将代词替换为如下所示的名词。

#input
'My sister has a dog. She loves him.'
'Angela lives in Boston. She is quite happy in that city.'

#output
'My sister has a dog. My sister loves a dog.'
'Angela lives in Boston. Angela is quite happy in Boston.'

错误

如何修复错误以获得适当的输出? 如果您有任何想法,请与我分享。

AttributeError: 'spacy.tokens.doc.Doc' object has no attribute 'replace'

当前代码

neuralcoref的使用示例代码如下网址:https://spacy.io/universe/project/neuralcoref

import spacy
import neuralcoref

nlp = spacy.load('en')
neuralcoref.add_to_pipe(nlp)
doc1 = nlp('My sister has a dog. She loves him.')
print(doc1._.coref_clusters)
print(doc1._.coref_clusters[0][1])
print(len(doc1._.coref_clusters))
for i in range(1, len(doc1._.coref_clusters)+1):
  doc_new = doc1.replace(doc1._.coref_clusters[0][i], doc1._.coref_clusters[1][i])

print(doc_new)

#output
[My sister: [My sister, She], a dog: [a dog, him]]
She
2

【问题讨论】:

  • 总是将完整的错误消息(从单词“Traceback”开始)作为文本(不是屏幕截图)放在有问题的(不是评论)中。还有其他有用的信息。
  • 先看print(doc1)print(type(doc1))——对我来说这是不正常的string有功能replace()。也许您应该将文本分配给变量text = 'My sister has a dog. She loves him.',然后您可以使用text.replace()

标签: python python-3.x nlp spacy


【解决方案1】:

neuralcoref 有一个特别专用的doc._.coref_resolved 方法来处理这样的任务:

import spacy
import neuralcoref

nlp = spacy.load('en_core_web_sm')
neuralcoref.add_to_pipe(nlp)
texts = ['My sister has a dog. She loves him.','Angela lives in Boston. She is quite happy in that city.']

docs = nlp.pipe(texts)
inp = []
out = []
for doc in docs:
    inp.append(doc.text)
    out.append(doc._.coref_resolved)

# desired output
print("Input:",inp)
print("Output:", out)
Input: ['My sister has a dog. She loves him.', 'Angela lives in Boston. She is quite happy in that city.']
Output: ['My sister has a dog. My sister loves a dog.', 'Angela lives in Boston. Angela is quite happy in Boston.']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-13
    • 1970-01-01
    • 2021-06-02
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    • 1970-01-01
    相关资源
    最近更新 更多