首页 > 解决方案 > 检查城市名称是否属于给定国家的最简单方法是什么?

问题描述

我有两个城市和国家名称列表,我想检查哪个城市属于哪个国家。在 python 中实现这一目标的最简单方法是什么?

请注意,到目前为止,我一直使用 GeoText 从测试中提取城市和国家名称,但它并没有告诉我哪个城市属于哪个国家。

该问题无法手动解决,因为列表很长。

例如

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

标签: pythongeotext

解决方案


你可以试试这段代码

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

此代码使用城市名称请求地理名称,而不是搜索到国家/地区的第一个链接,您可以更改它并使用 beautifulsoup 使其更优雅。如果您在大型列表上运行此代码,请注意这需要时间,因为他等待 geoname 的响应!

示例输出:

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']}

推荐阅读