Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:GoogleMapsAPI发送未知格式进行解析_Python_Google Maps_Parsing_Google Api_Extract - Fatal编程技术网

Python:GoogleMapsAPI发送未知格式进行解析

Python:GoogleMapsAPI发送未知格式进行解析,python,google-maps,parsing,google-api,extract,Python,Google Maps,Parsing,Google Api,Extract,我使用从google maps获取以下数据: { 'address_components':[ { 'long_name':'20', 'short_name':'20', 'types':[ 'street_number' ] }, { 'long_name':'Oberböhl', 'short_na

我使用从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'
   ]
}
问题是,索引“0”并不总是我想要的数据的相同位置,我会改变。有没有其他方法提取数据?也许我必须使用JSON解析器或类似的东西

非常感谢。

答案是:

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

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


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

为什么只需剥离第0个元素就可以生成整个列表使用带有
next()
的生成器表达式,在大多数方面与列表理解非常相似:
match=next((c表示c中的就地结果[“地址组件”],如果在c中键入[“类型”]),则无);return match[property]
可能不会使用
type
property
作为变量名tho。我的目的不是要制作最具python风格的解决方案,而是提供一些防止OP将这段代码复制粘贴13次的功能。因此它更具体一点。地址中最有趣的部分(门牌号、街道、州等)无论如何只会出现一次,所以这就是我所做的权衡。关于变量名,你是绝对正确的,我会更改它们。
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")