user13390730
user13390730

Reputation:

How to find city names in string using NLP and Python

As you can see in the title, my question is simple. I want to find city names using NLP. Here is an example:

Question:

How is the weather today in Istanbul?

Answer:

["Istanbul"]

I tried this code but it didn't help me so much.

import nltk   
my_sent = "How is the weather in Izmit"

word = nltk.word_tokenize(my_sent)   
pos_tag = nltk.pos_tag(word)   
chunk = nltk.ne_chunk(pos_tag)   
NE = [ " ".join(w for w, t in ele) for ele in chunk if isinstance(ele, nltk.Tree)]   
print(NE)

How can I get this result? Thanks for your answers.

Upvotes: 1

Views: 1360

Answers (1)

Rami Janini
Rami Janini

Reputation: 593

This can be done with spacy package:

First you should install spacy and load the en_core_web_ln:

python3 -m pip install spacy 
python3 -m spacy download en_core_web_lg

Then use the code below:

import spacy

nlp = spacy.load('en_core_web_lg')

doc = nlp(u'How is the weather in Izmit')

for ent in doc.ents:
    print(ent.text)

Upvotes: 1

Related Questions