使用python 3从googlemaps api响应中提取数据
我正在使用使用python 3从googlemaps api响应中提取数据,python,python-3.x,google-maps,Python,Python 3.x,Google Maps,我正在使用googlemaps库查询googlemapsapi。我想根据邮政编码提取一个城市的名称 例如,对于邮政编码23325,我想提取切萨皮克的邮政编码 这是我的初始代码: import googlemaps from keys import google_api_key gmaps = googlemaps.Client(key=google_api_key) geocode_result = gmaps.geocode('23325') print(geocode_result) 以
googlemaps
库查询googlemapsapi。我想根据邮政编码提取一个城市的名称
例如,对于邮政编码23325,我想提取切萨皮克的邮政编码
这是我的初始代码:
import googlemaps
from keys import google_api_key
gmaps = googlemaps.Client(key=google_api_key)
geocode_result = gmaps.geocode('23325')
print(geocode_result)
以下是打印地理编码结果的结果:[{'address_components':[{'long_name':'23325','short_name':'23325','types':['postal_code']},{'long_name':'Indian River','short_name':'Indian River','types':['neighbour','political']},{'long_name':'Chesapeake','short_name':'Chesapeake','typeake','typeake':['locality','political']},{'long_name':'Virginia','short_name':'VA','types':['administration_area_level_1','political']},{'long_name':'US','types':['country','political']},'formatted_address':'Chesapeake,va23325,USA','geometry':{'bounds':{'northeast':{'northeast':{'lat 36.8399469','lng':-76.2193310999999},'{'lat':36.7870261,'lng':-76.2574748999999},'location':{'lat':36.8179707,'lng':-76.2305308},'location'u type':'近似','viewport':{'northeast':{'lng':36.8399469,'lng':-76.2193310999999},'西南':{'lat 36.7870261,'lng':-76.25748999999},'place id':'chicvjt9cquzmuzmu},'
当我看到类型时打印(键入(地理编码\u结果))
Python告诉我
如果我尝试类似于geocode\u result[1]
的任何操作,我会收到以下错误消息:
索引器错误:列表索引超出范围
如果我尝试geocode\u结果['address\u components']
我会得到一个TypeError:列表索引必须是整数或片,而不是str
消息
非常感谢您的帮助!谢谢!您有一个dicts列表。因此,您可以使用列表索引获取第一项,然后使用键获取dict元素 例如:
item = geocode_result[0]
item['address_components'] # Returns another list
item['formatted_address'] # Returns a string 'Chesapeake, VA 23325, USA'
这是反向地理编码。这可以做到:
import urllib, json
import urllib.request
geocode = input("Enter zip code : ")
url = "https://maps.googleapis.com/maps/api/geocode/json?&address=" + geocode
response = urllib.request.urlopen(url)
data = json.loads(response.read())
print(data)
当你尝试
geocode\u结果[0]
时会发生什么?我得到的结果与打印geocode\u结果相同。我尝试使用bytes.decode…但我真的不知道我在做什么。糟糕!如果我有个孩子在路上,我会以你的名字命名!非常感谢!我使用了你的建议item=geocode\u结果[0]
,然后x=item>['formatted_address']
。然后我使用x2=x.split(“,”[0]
提取城市名称。