如何在Spacy的句子中获取实体的索引?

iCH*_*AIT 5 python nlp spacy

我想知道是否有一种优雅的方法来获取实体相对于句子的索引。我知道我可以使用ent.start_charand获取字符串中实体的索引ent.end_char,但该值是相对于整个字符串的。

import spacy

nlp = spacy.load("en_core_web_sm")
doc = nlp(u"Apple is looking at buying U.K. startup for $1 billion. Apple just launched a new Credit Card.")

for ent in doc.ents:
    print(ent.text, ent.start_char, ent.end_char, ent.label_)
Run Code Online (Sandbox Code Playgroud)

我希望Apple两个句子中的实体分别指向开始和结束索引 0 和 5。我怎样才能做到这一点?

Wik*_*żew 8

您需要从实体开始位置减去句子开始位置:

for ent in doc.ents:
    print(ent.text, ent.start_char-ent.sent.start_char, ent.end_char-ent.sent.start_char, ent.label_)
#                                 ^^^^^^^^^^^^^^^^^^^^              ^^^^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

输出:

Apple 0 5 ORG
U.K. 27 31 GPE
$1 billion 44 54 MONEY
Apple 0 5 ORG
Credit Card 26 37 ORG
Run Code Online (Sandbox Code Playgroud)