在Python

时间:2016-06-05 06:22:10

标签: python python-3.x google-maps-api-3

我使用Python 3和Google地理编码API来收集地址信息。我很难一直解析出我要回复的地址组件。 'address_components'部分的JSON结构似乎不遵循标准的json格式,我找不到任何提及如何通过名称弹出列表中的值,也许我需要强制'address_components'列表部分的行为像字典? 具体来说,我的问题出现在类似下面的情况:

import urllib.request
import urllib.parse
import json

url = "http://maps.googleapis.com/maps/api/geocode/json?" + urllib.parse.urlencode({"sensor": "false", "output": "more", "address": "The White House"})
uo = urllib.request.urlopen(url)
data = uo.read().decode()
js = json.loads(str(data))
print('Full js:', js)
# which nets good json text as inserted in-line below:
  

Full js:{'results':[{'formatted_address':'The White House,1600 Pennsylvania Ave NW,Washington,DC 20500,USA','geometry':{'location':{'lng': - 77.0365298,'lat':38.8976763},'viewport':{'southwest':{'lng': - 77.0378787802915,'lat':38.8963273197085},'northeast':{'lng': - 77.0351808197085,'lat':38.8990252802915 },'location_type':'APPROXIMATE'},'address_components':[{'long_name':'白宫','类型':['point_of_interest','建立'],'short_name':'白宫'},{'long_name':'1600','types':['street_number'],'short_name':'1600'},{'long_name':'Pennsylvania Avenue Northwest','types':['route' ],'short_name':'Pennsylvania Ave NW'},{'long_name':'西北华盛顿','类型':['邻域','政治'],'short_name':'西北华盛顿'},{'long_name ':'华盛顿','类型':['locality','political'],'short_name':'Washington'},{'long_name':'哥伦比亚特区','类型':['administrative_area_level_1','政治'','short_name':'D C'},{'long_name':'美国','类型':['country','political'],'short_name':'US'},{'long_name':'20500','types': ['postal_code'],'short_name':'20500'}],'partial_match':是的,'place_id':'ChIJ37HL3ry3t4kRv3YLbdhpWXE','types':['point_of_interest','establishment']}],'status': 'OK'}

# Thanks to the json library (I believe), I can pull data out of the above as if it were a mixed list & dictionary by using named references and indexed locations:
rte = js['results'][0]['address_components'][2]
print("Route:", rte)
  

路线:{'long_name':'Pennsylvania Avenue Northwest','types':['route'],'short_name':'Pennsylvania Ave NW'}

# unfortunately though, the lists change structure (after the initial 'results' category) and so the route is not always the third element, as seen below:
url2 = "http://maps.googleapis.com/maps/api/geocode/json?" + urllib.parse.urlencode({"sensor": "false", "output": "more", "address": "The Breakers"})
uo2 = urllib.request.urlopen(url2)
data2 = uo2.read().decode()
js2 = json.loads(str(data2))
address_components2 = js2['results'][0]['address_components'][2]
print("address_components2:", address_components2)
  

address_components2:{'long_name':'萨福克郡','类型':['administrative_area_level_2','政治'],'short_name':'萨福克郡'}

有没有解决这个问题的方法?如何为“路线”提供路线

1 个答案:

答案 0 :(得分:0)

正如Processing JSON with Javascript中的Python示例所讨论和显示的那样,json.load()用于解析,然后结果以formatted_address值显示给数组中的用户。而且,为了只获取您需要的数据,只要JSON响应包含多个值,您就可以使用Python Built-in Functions中的filter()函数。

有关处理JSON响应的有用解释也可以在此相关的SO帖子中找到 - How to reverse geocode serverside with python, json and google maps?