Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can I Determine a Region, Country, and Continent Based on a City Using Python?

Tags:

python

So, I have a list of a bunch of city and state/region combinations (where some cities do not have a paired state/region) and I'd like to use these to fill in country, continent, (and state/region where it's not supplied) information. Where multiple regions would fit, I'm willing to accept any of them, though the biggest one would be best. What's the simplest library for Python that will let me do this?

An example: given "Istanbul," I'd want something like:

{istanbul, istanbul province, turkey, europe}

like image 315
Eli Avatar asked Feb 26 '23 06:02

Eli


2 Answers

Thanks to Kimvais and Lennart Regebro, I've figured out a pretty simple way of doing what I wanted, and I wanted to post the basic steps here for anyone else who has the same problem.

  1. Install geopy (http://code.google.com/p/geopy/)

  2. Use the following:

     from geopy import geocoders
    
     gn = geocoders.Google()
     place, (lat, lng) = gn.geocode("istanbul")
     print place
    

This prints: Istanbul/Istanbul Province, Turkey, which is awesome and exactly what I wanted (sans the continent part, but that's pretty easy to do on my own with just a list of country/continent combos (yes I'm aware Turkey is in 2 different continents. I'm happy just placing it in one for my purposes since it doesn't matter too much to me).

like image 91
Eli Avatar answered Feb 27 '23 20:02

Eli


You don't need any library for this at all, really. What you do need is a list of geographic locations. If you don't have that there are geolocation services online you can use, that will do these things for you, accessible via http (and hence urllib). You might need a library to interpret the response, that could be XML, for example.

like image 41
Lennart Regebro Avatar answered Feb 27 '23 20:02

Lennart Regebro