Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spacy: get position of word with entity tag

Tags:

spacy

I'm trying to get the position of a word and it's entity tag by iterating over a sentence, as per the spacy docs

import spacy
nlp = spacy.load('en')
doc = nlp(u'London is a big city in the United Kingdom.')
for ent in doc.ents:
    print(ent.label_, ent.text)
    # GPE London
    # GPE United Kingdom

I've tried to get the position of the word with the tag ent.i and ent.idx however neither of these work and give the following error

AttributeError: 'spacy.tokens.span.Span' object has no attribute 'i'
like image 266
jack west Avatar asked Sep 18 '25 03:09

jack west


1 Answers

It would appear to be ent.start

import spacy
nlp = spacy.load('en')
doc = nlp(u'London is a big city in the United Kingdom.')
for ent in doc.ents:
    print(ent.label_, ent.text, ent.start)
    #GPE London 0
    #GPE the United Kingdom 6
like image 180
jack west Avatar answered Sep 22 '25 19:09

jack west