In using Spacy, I have the following:
JavaScript
x
13
13
1
import spacy
2
3
nlp = spacy.load('en_core_web_lg')
4
5
sentence = "a quick John jumps over the lazy dog"
6
7
tag_entities = [(x, x.ent_iob_, x.ent_type_) for x in nlp(sentence)]
8
inputlist = tag_entities
9
10
print (inputlist)
11
12
[(a, 'O', ''), (quick, 'O', ''), (John, 'B', 'PERSON'), (jumps, 'O', ''), (over, 'O', ''), (the, 'O', ''), (lazy, 'O', ''), (dog, 'O', '')]
13
It is a list of tuples. I want to extract the person element. This is what I do:
JavaScript
1
6
1
for i in inputlist:
2
if (i)[2] == "PERSON":
3
print ((i)[0])
4
5
John
6
What would be a better way?
Advertisement
Answer
To keep all first element if second element is PERSON
from first list use a list comprehension notation with a if
at the end
JavaScript
1
2
1
filtered_taglist = [x for x,_,type in tag_entities if type == "PERSON"]
2
This corresponds to
JavaScript
1
5
1
filtered_taglist = []
2
for x,_,type in inputlist:
3
if type == "PERSON":
4
filtered_taglist.append(x)
5