Question

I have this code.

from nltk import pos_tag, ne_chunk
import nltk.chunk
from nltk.corpus import names
qry = "who is Ronald Avon"
tokens = nltk.tokenize.word_tokenize(qry)
pos = nltk.pos_tag(tokens)
sentt = nltk.ne_chunk(pos, binary = False)
person = []
for subtree in sentt.subtrees(filter=lambda t: t.node == 'PERSON'):
    for leave in subtree.leaves():
        person.append(leave)
print "person=", person

It gets names in a sentence. This is the result I get.

person= [('Ronald', 'NNP'), ('Avon', 'NNP')]

How do i get the result like this:

Ronald
Avon

without the 'NNP' and the parentheses. Thanks.

Was it helpful?

Solution

Use a list comprehension.

To get an array of the names:

names = [name for name, tag in person]

To output a string in the format you give:

# Python 2 (print is a statement)
print "\n".join([name for name, tag in person])

# Python 3 (print is a function)
print("\n".join([name for name, tag in person]))

This is really a basic Python data structure question - it's not specific to NLTK. You might find an introductory guide like An informal guide to Python useful.

OTHER TIPS

Something like that?

>>>for z in [i for i,y in person]: print z
Ronald
Avon
>>>
for subtree in sentt.subtrees(filter=lambda t: t.node == 'PERSON'):
    for name, tag in subtree.leaves():
        person.append(name)

print('\n'.join(person))

Without knowing NLTK, it seems you're going to have to make some assumptions about the structure of returned data, namely, whether it is consistently a 2-element list of 2-element tuples. From the looks of it, you could do something like this:

person.append("%s %s" % (leave[0][0], leave[1][0]))

If you wanted to print "Ronald Avon".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top