有没有一种简单的方法可以通过spacy顺序获取令牌的位置?

时间:2020-07-07 01:02:29

标签: nlp spacy

我想要序列中每个令牌的开始索引和结束索引。有没有简单的方法可以做到这一点?

例如:

text='Brown is a nice guy'
spacy_doc=nlp(text)

for sent in spacy_doc.sents:
    for token in sent:
        print(token.text, token.i)

    
Brown 0
is 1
a 2
nice 3
guy 4

这不是我所需要的。我需要

Brown 0,4
is 6,7
a 9,9
nice 11,14
guy 16,18

1 个答案:

答案 0 :(得分:2)

import spacy

text = 'Brown is a nice guy'
nlp = spacy.load("en_core_web_sm")
doc = nlp(text)

for token in doc:
  print(token.text, token.idx, token.idx + len(token.text) - 1)

输出

Brown 0 4
is 6 7
a 9 9
nice 11 14
guy 16 18