python - 检查城市名称是否属于给定国家的最简单方法是什么?
问题描述
我有两个城市和国家名称列表,我想检查哪个城市属于哪个国家。在 python 中实现这一目标的最简单方法是什么?
请注意,到目前为止,我一直使用 GeoText 从测试中提取城市和国家名称,但它并没有告诉我哪个城市属于哪个国家。
该问题无法手动解决,因为列表很长。
例如
country_list = ['china', 'india', 'canada', 'america', ...]
city_list = ['Mocoa', 'March', 'San Miguel', 'Neiva', 'Naranjito', 'San Fernando',
'Alliance', 'Progreso', 'NewYork', 'Toronto', ...]
解决方案
你可以试试这段代码
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']}
推荐阅读
- python-3.x - BeautifulSoup.find() is returning None, unable to access table on wiki page
- javascript - (初学者问题)如何从 OpenWeatherMap API 获取特定数据
- css - CSS applied to all pages but one - Ruby/Sinatra
- ios - 仅从 Apple Watch 获取位置更新(即使连接了 iPhone)
- go - 当我使用 chan 传递参数时,我没有得到预期的结果
- python - 为什么我的变量应该是全局变量却被认为是局部变量?
- ios - 如何在 Swift 中将 PNG 转换为 WebP?
- julia - 工作目录是否在函数内部发生变化?
- ios - 致命错误:对 Swift 类使用未实现的初始化程序“init()”
- r - 使用 ggplot2 创建类似于 d3.js 强制布局的气泡图