从地址中提取国家和城市及其计数可以通过以下步骤实现:
以下是一个示例代码,使用Python语言和腾讯地图的地理编码和逆地理编码API实现上述功能:
import requests
def extract_country_city(address):
# 地理编码
geocoding_url = "https://apis.map.qq.com/ws/geocoder/v1/"
params = {
"address": address,
"key": "YOUR_TENCENT_MAP_API_KEY"
}
response = requests.get(geocoding_url, params=params)
geocoding_data = response.json()
# 获取经纬度坐标
location = geocoding_data["result"]["location"]
lat = location["lat"]
lng = location["lng"]
# 逆地理编码
reverse_geocoding_url = "https://apis.map.qq.com/ws/geocoder/v1/"
params = {
"location": f"{lat},{lng}",
"key": "YOUR_TENCENT_MAP_API_KEY"
}
response = requests.get(reverse_geocoding_url, params=params)
reverse_geocoding_data = response.json()
# 提取国家和城市信息
country = reverse_geocoding_data["result"]["address_component"]["nation"]
city = reverse_geocoding_data["result"]["address_component"]["city"]
return country, city
# 示例地址
address_list = [
"北京市海淀区中关村大街27号",
"上海市浦东新区世纪大道100号",
"广东省深圳市南山区高新南一道",
"江苏省南京市鼓楼区汉口路1号"
]
# 统计计数
country_city_count = {}
for address in address_list:
country, city = extract_country_city(address)
if (country, city) in country_city_count:
country_city_count[(country, city)] += 1
else:
country_city_count[(country, city)] = 1
# 输出结果
for (country, city), count in country_city_count.items():
print(f"{country} {city}: {count}")
请注意,上述示例代码中的YOUR_TENCENT_MAP_API_KEY
需要替换为您自己的腾讯地图API密钥。此外,该示例代码仅提供了一个基本的实现思路,实际应用中可能需要根据具体需求进行适当的修改和优化。
领取专属 10元无门槛券
手把手带您无忧上云