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

Python 如何在Spacy中获取句子中实体的索引?,python,nlp,spacy,Python,Nlp,Spacy,我想知道是否有一种优雅的方法来获取实体相对于句子的索引。我知道我可以使用ent.start\u char和ent.end\u char获取字符串中实体的索引,但该值与整个字符串有关 导入空间 nlp=spacy.load(“en_core\u web\u sm”) NLP(U)苹果正在考虑以10亿美元的价格收购英国创业公司。苹果刚刚推出了一张新的信用卡。 对于doc.ents中的ent: 打印(ent.text、ent.start\u char、ent.end\u char、ent.label\

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

导入空间
nlp=spacy.load(“en_core\u web\u sm”)
NLP(U)苹果正在考虑以10亿美元的价格收购英国创业公司。苹果刚刚推出了一张新的信用卡。
对于doc.ents中的ent:
打印(ent.text、ent.start\u char、ent.end\u char、ent.label\ux)

我希望两个句子中的实体
Apple
分别指向起始索引0和结束索引5。我该怎么做呢?

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

for ent in doc.ents:
    print(ent.text, ent.start_char-ent.sent.start_char, ent.end_char-ent.sent.start_char, ent.label_)
#                                 ^^^^^^^^^^^^^^^^^^^^              ^^^^^^^^^^^^^^^^^^^^
输出:

Apple 0 5 ORG
U.K. 27 31 GPE
$1 billion 44 54 MONEY
Apple 0 5 ORG
Credit Card 26 37 ORG

谢谢这正是我所需要的。