首页 > 解决方案 > Python:Google-Maps-API 发送未知格式进行解析

问题描述

我使用Python Client for Google Maps Services从 google-maps 获取以下数据:

{  
   'address_components':[  
      {  
         'long_name':'20',
         'short_name':'20',
         'types':[  
            'street_number'
         ]
      },
      {  
         'long_name':'Oberböhl',
         'short_name':'Oberböhl',
         'types':[  
            'route'
         ]
      },
      {  
         'long_name':'Ingelheim am Rhein',
         'short_name':'Ingelheim am Rhein',
         'types':[  
            'locality',
            'political'
         ]
      },
      {  
         'long_name':'Mainz-Bingen',
         'short_name':'Mainz-Bingen',
         'types':[  
            'administrative_area_level_3',
            'political'
         ]
      },
      {  
         'long_name':'Rheinland-Pfalz',
         'short_name':'RP',
         'types':[  
            'administrative_area_level_1',
            'political'
         ]
      },
      {  
         'long_name':'Germany',
         'short_name':'DE',
         'types':[  
            'country',
            'political'
         ]
      },
      {  
         'long_name':'55218',
         'short_name':'55218',
         'types':[  
            'postal_code'
         ]
      }
   ],
   'adr_address':'<span class="street-address">Oberböhl 20</span>, <span class="postal-code">55218</span> <span class="locality">Ingelheim am Rhein</span>, <span class="country-name">Germany</span>',
   'formatted_address':'Oberböhl 20, 55218 Ingelheim am Rhein, Germany',
   'formatted_phone_number':'06132 5099968',
   'geometry':{  
      'location':{  
         'lat':49.9810156,
         'lng':8.0739617
      },
      'viewport':{  
         'northeast':{  
            'lat':49.9823942302915,
            'lng':8.075293780291501
         },
         'southwest':{  
            'lat':49.9796962697085,
            'lng':8.072595819708498
         }
      }
   },
   'icon':'https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png',
   'id':'d2b37ffe23fd5e76648a90df2987558b039fcdf7',
   'international_phone_number':'+49 6132 5099968',
   'name':'Esch Metalltechnik GmbH',
   'place_id':'ChIJHaERGJ_svUcRRfqNoGXq3EU',
   'plus_code':{  
      'compound_code':'X3JF+CH Ingelheim am Rhein, Germany',
      'global_code':'8FXCX3JF+CH'
   },
   'reference':'ChIJHaERGJ_svUcRRfqNoGXq3EU',
   'scope':'GOOGLE',
   'types':[  
      'general_contractor',
      'point_of_interest',
      'establishment'
   ],
   'url':'https://maps.google.com/?cid=5034156205699627589',
   'utc_offset':60,
   'vicinity':'Oberböhl 20, Ingelheim am Rhein',
   'website':'http://www.esch-metalltechnik.de/'
}{  
   'long_name':'55218',
   'short_name':'55218',
   'types':[  
      'postal_code'
   ]
}

现在我想提取某些变量,例如"street_number". 我不知道这个数据是哪种格式,所以我像字典一样使用它:

try:
    self.hausnr = place_result_2["address_components"][0]["long_name"]
except:
    self.hausnr = "NA"

问题是,索引“0”并不总是我想要的数据的相同位置,我会有所不同。有没有办法以另一种方式提取数据?也许我必须使用 JSON 解析器或类似的东西?

非常感谢。

标签: pythongoogle-mapsparsinggoogle-apiextract

解决方案


答案是:列表推导

try:
    # make a list of all address components that have type "street number"
    comp = [c for c in place_result_2["address_components"] if "street_number" in c["types"]]

    # the first one of them (assuming there will never be more than one) is the desired one
    self.hausnr = comp[0]["long_name"]
except:
    self.hausnr = "NA"

因为这可能是一个常见的操作,所以创建一个函数:

def get_address_component(place_result, comp_type, comp_property="long_name", default=None):
    """ returns the first address component of a given type """
    try:
        comp = [c for c in place_result["address_components"] if comp_type in c["types"]]
        return comp[0][comp_property]
    except KeyError:
        return default

# ...

self.hausnr = get_address_component(place_result_2, "street_number", default="NA")

PS,关于:

也许我必须使用 JSON 解析器或类似的东西?

JSON 是一种数据传输格式 - 它是纯文本。Google API 服务器使用它通过网络获取数据。在您的程序中,它已经被您正在使用的 Google API 客户端库解析。您正在查看的不再是 JSON,而是 Python 数据结构(嵌套的字典、列表和值)。当您将它打印到控制台时,它恰好看起来与 JSON 非常相似,因为 Python 使用类似的格式来表示数据。

换句话说,不,您不需要再次对其进行 JSON 解析。


推荐阅读