You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从原始地址字符串提取州、城市、国家、邮编及街道信息

可行方案:利用Google Geocoding API提取地址组件

当然可以实现,你已经完成了API调用的核心部分,接下来只需要解析返回结果中的address_components字段,根据每个组件的types属性匹配对应的地址信息即可。

修改后的完整代码

import requests

API_KEY = "AIzaSyAeVWl5w9M5JvfCsIUH18435VGHVc"
address = "322 DURANGO DOWNS DR HUTTO, Texas 78634 United States"

params = {
    'key': API_KEY,
    'address': address
}
url = "https://maps.googleapis.com/maps/api/geocode/json?"
response = requests.get(url, params=params).json()

# 初始化提取结果容器
address_info = {
    'street': '',
    'city': '',
    'state': '',
    'postal_code': '',
    'country': ''
}

# 解析地址组件
if response.get('status') == 'OK':
    components = response['results'][0]['address_components']
    for component in components:
        types = component['types']
        if 'street_number' in types or 'route' in types:
            # 拼接街道号码与街道名称
            address_info['street'] += f"{component['long_name']} "
        elif 'locality' in types:
            address_info['city'] = component['long_name']
        elif 'administrative_area_level_1' in types:
            address_info['state'] = component['long_name']
        elif 'postal_code' in types:
            address_info['postal_code'] = component['long_name']
        elif 'country' in types:
            address_info['country'] = component['long_name']
    
    # 清理街道字段末尾的多余空格
    address_info['street'] = address_info['street'].strip()
    
    # 输出提取结果
    print("提取的地址信息:")
    for key, value in address_info.items():
        print(f"{key}: {value}")
else:
    print(f"API请求失败,状态码:{response.get('status')}")

核心逻辑说明

API返回的address_components数组是提取地址信息的关键,每个元素对应一个地址组成部分,通过types属性区分类型:

  • street_number(街道号码)+ route(街道名称):组合为完整街道信息
  • locality:对应城市(部分地区可能使用sublocality,需根据实际地址场景调整)
  • administrative_area_level_1:对应州/省一级行政区
  • postal_code:邮政编码
  • country:国家名称

注意事项

  • 确保API密钥有效且有足够的调用额度
  • 不同国家/地区的地址组件类型可能存在差异,需根据实际场景调整判断逻辑
  • 必须处理API返回的status字段,避免请求失败时出现程序报错

内容的提问来源于stack exchange,提问作者Ajay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 15:17:11