[英]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?
在 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.请注意,到目前为止,我一直使用 GeoText 从测试中提取城市和国家名称,但它并没有告诉我哪个城市属于哪个国家。
The problem can't be solved manually because the lists are long.该问题无法手动解决,因为列表很长。
EG例如
country_list = ['china', 'india', 'canada', 'america', ...]
city_list = ['Mocoa', 'March', 'San Miguel', 'Neiva', 'Naranjito', 'San Fernando',
'Alliance', 'Progreso', 'NewYork', 'Toronto', ...]
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.此代码使用城市名称请求地理名称,而不是搜索到国家/地区的第一个链接,您可以更改它并使用 beautifulsoup 使其更优雅。 if you run this code on large list notice that it takes time because he wait for response from geoname!
如果您在大型列表上运行此代码,请注意这需要时间,因为他等待 geoname 的响应!
example output:例如 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']}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.