如何在 spaCy 中获取句子中标记的索引?

How to get the index of a token in a sentence in spaCy?

有没有一种优雅的方法来获取 word/token 在其句子中的索引? 我知道令牌的属性 https://spacy.io/api/token#attributes i 属性 returns 整个父文档中的索引。但是父文档可以包含多个句子。

示例:

"This is an example. This is another example."

我需要的是 "This" 作为索引 0 返回,"is" 作为索引 1 返回等等...

spaCy Doc 对象还允许您迭代 doc.sents,即单个句子的 Span objects。要在父文档中获取跨度的开始和结束索引,您可以查看 startend 属性。因此,如果您遍历句子并从 token.i 中减去句子开始索引,您将得到标记在句子中的相对索引:

for sent in doc.sents:
    for token in sent:
        print(token.text, token.i - sent.start)

默认的分句使用依赖解析,通常更准确。但是,您也可以插入基于规则或完全自定义的解决方案(see here 了解详情)。