Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

python - What is the easiest way to check if a city name belongs to a given country?

I have two lists of city and country names, and I would like to check which city belong to which country. What is the easiest way to achieve that in python?

Please note that I have used till now GeoText to extract city and country names from a test but it doesn't tell me which city belongs to which country.

The problem can't be solved manually because the lists are long.

E.G.

country_list = ['china', 'india', 'canada', 'america', ...]
city_list = ['Mocoa', 'March', 'San Miguel', 'Neiva', 'Naranjito', 'San Fernando',
             'Alliance', 'Progreso', 'NewYork', 'Toronto', ...]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you can try this code

import requests
import re

city_list = ['Jerusalem', 'Tel-Aviv', 'New York', 'London', 'Madrid', 'Alliance',
             'Mocoa', 'March', 'San Miguel', 'Neiva', 'Naranjito', 'San Fernando',
             'Alliance', 'Progreso', 'NewYork', 'Toronto']
city_country_dict = {}
country_city_dict = {}
for city in city_list:
    response = requests.request("GET", f"https://www.geonames.org/search.html?q={city}&country=")
    country = re.findall("/countries.*.html", response.text)[0].strip(".html").split("/")[-1]
    if country not in country_city_dict:
        country_city_dict[country] = [city]
    else:
        country_city_dict[country].append(city)
    city_country_dict[city] = country

this code make request to geoname with city name and than search for the first link to country, you can change this and use beautifulsoup to make it more elegant. if you run this code on large list notice that it takes time because he wait for response from geoname!

example output:

city_country_dict = {'Jerusalem': 'israe', 'Tel-Aviv': 'israe', 'New York': 'united-states', 'London': 'united-kingdo', 'Madrid': 'spain', 'Alliance': 'united-states', 'Mocoa': 'colombia', 'March': 'switzerland', 'San Miguel': 'el-salvador', 'Neiva': 'colombia', 'Naranjito': 'puerto-rico', 'San Fernando': 'trinidad-and-tobago', 'Progreso': 'honduras', 'NewYork': 'united-kingdo', 'Toronto': 'canada'}


country_city_dict = {'israe': ['Jerusalem', 'Tel-Aviv'], 'united-states': ['New York', 'Alliance', 'Alliance'], 'united-kingdo': ['London', 'NewYork'], 'spain': ['Madrid'], 'colombia': ['Mocoa', 'Neiva'], 'switzerland': ['March'], 'el-salvador': ['San Miguel'], 'puerto-rico': ['Naranjito'], 'trinidad-and-tobago': ['San Fernando'], 'honduras': ['Progreso'], 'canada': ['Toronto']}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...