遍历 python 中的地理编码 API 响应

Iterating through Geocoding API response in python

我试图在反向地理编码 Google 地图 API 中找到 ['locality', 'political'] 值。

我可以在 Javascript 中实现相同的效果,如下所示:

var formatted = data.results;
$.each(formatted, function(){
     if(this.types.length!=0){
          if(this.types[0]=='locality' && this.types[1]=='political'){
               address_array = this.formatted_address.split(',');
          }else{
               //somefunction
          }
     }else{
         //somefunction
     }
});

使用 Python,我尝试了以下操作:

url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng='+lat+','+long+'&result_type=locality&key='+MAPS_API_KEY
results = json.loads(urllib.request.urlopen(url).read().decode('utf-8'))
city_components = results['results'][0]
for c in results:
    if c['types']:
        if c['types'][0] == 'locality':
            print(c['types'])

这给了我一堆错误。我无法通过遍历响应对象找到 ['locality', 'political'] 值来找到相关的城市 short_name。我该如何解决这个问题?

您正在尝试访问字典的键,但您正在迭代该键的字符:

for c in results:
    if c['types']:

results 是一本字典(从您的 city_components= 行可以看出)。当您键入 for c in results 时,您将 c 绑定到该字典的键(依次)。这意味着 c 是一个字符串(在您的场景中,很可能所有键都是字符串)。所以然后键入 c['types'] 没有意义:您正在尝试访问字符串的 value/attribute 'types'...

您最有可能想要:

for option in results['results']:
    addr_comp = option.get('address_components', [])
    for address_type in addr_comp:
        flags = address_type.get('types', [])
        if 'locality' in flags and 'political' in flags:
            print(address_type['short_name'])