find named entities from tokenized sentences in SPACY v2.0

Viewed 1915

I am trying to do:

  • Tokenize sentences from text
  • Compute Named Entities for each word present in sentence

This is what I have done so far:

nlp = spacy.load('en')
sentence = "Germany and U.S.A are popular countries. I am going to gym tonight"
sentence = nlp(sentence)
tokenized_sentences = []
for sent in sentence.sents:
        tokenized_sentences.append(sent)
for s in tokenized_sentences:
        labels = [ent.label_ for ent in s.ents]
        entities = [ent.text for ent in s.ents]

Error:

    labels = [ent.label_ for ent in s.ents]
    AttributeError: 'spacy.tokens.span.Span' object has no attribute 'ents'

Is there any alternative way to find named entities of tokenized sentence?

Thanks in advance

2 Answers

Note that you only have two entities - USA and Germany.

The simple version:

sentence = nlp("Germany and U.S.A are popular countries. I am going to gym tonight")    
for ent in sentence.ents:
        print(ent.text, ent.label_)

What i think you are tying to do:

sentence = nlp("Germany and U.S.A are popular countries. I am going to gym tonight")
for sent in sentence.sents:
    tmp = nlp(str(sent))
    for ent in tmp.ents:
        print(ent.text, ent.label_)

ents works only with doc (spacy.tokens.doc.Doc), if you use doc=nlp(text)

sent is of type spacy.tokens.span.Span which has no ents method.

Convert it to text and use nlp() again.

print([(ent.text, ent.label_) for ent in nlp(sent.text).ents])
Related