I am trying to get GPE locations from a message after tokenizing it.
from nltk import ne_chunk
print(ne_chunk(pos_words[0]))
Output:
Weather/NNP
update/VB
a/DT
cold/JJ
front/NN
from/IN
(GPE Cuba/NNP)
that/WDT
could/MD
pass/VB
over/RP
(PERSON Haiti/NNP))
I want to get the output Cuba as a string. How can I access that?
Edit: I am trying to generalize the extraction to the dataframe by making a list of locations. This is the function I made. However, it splits multi-word locations like New York into [New, York]
locations = []
for i in range(len(pos_words)):
chunks = ne_chunk(pos_words[i])
for c in chunks:
if isinstance(c, Tree) and c.label() == 'GPE':
# The object is <class 'nltk.tree.Tree'> and label is Geopolitical Entity
locations.extend([w for w,_ in c.leaves()])
return locations
import nltk
from nltk import Tree
text = 'Weather update a cold front from Cuba that could pass over Hatti'
# Tokenize and tag
pos_words = nltk.pos_tag(nltk.word_tokenize(text))
# Named entity chunker
chunks = nltk.ne_chunk(pos_words)
for c in chunks:
if isinstance(c, Tree) and c.label() == 'GPE':
# The object is <class 'nltk.tree.Tree'> and label is Geopolitical Entity
print(' '.join([w for w, _ in c.leaves()]))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.