Change name of any state, county, regions, or their abbreviations to country name in python NLTK or other packages

208 Views Asked by At

I have a list of locations that is mixed with states, cities and countries, counties and regions, in abbreviations and some in full. For instance, NY, CA, England, UK, USA, Minnesota, London, Bradford, etc. I want it all to be converted to countries such as NY=USA, England=UK, Scotland = UK, Minnesota = USA, etc.

I want a package or library that I can use in my program to change any of the abbreviations, states, state codes, or any city to the country of the locations. So if you London, it should return the UK, Chicago to return the US, and so on.

Is it possible to achieve this in python? Thanks in advance.

1

There are 1 best solutions below

0
On

You can use the Geopy Python library.

from functools import partial
from geopy.geocoders import Nominatim

geolocator = Nominatim(user_agent="my_app")

geocode = partial(geolocator.geocode, language="es")
print(geocode("paris", language="en"))
>>>Paris, Ile-de-France, Metropolitan France, France

From this, you will get the complete address. you can just grab the last word.

text = geocode("paris", language="en")
last_word = text.rsplit(', ', 1)[-1]

Certainly, if you are working with very large data and efficiency is a concern, you might consider optimizing the code.