Python|Python 小项目2 使用JSON API并处理数据

In this assignment you will write a Python program somewhat similar to http://www.py4e.com/code3/geojson.py. The program will prompt for a location, contact a web service and retrieve JSON for the web service and parse that data, and retrieve the first place_id from the JSON. A place ID is a textual identifier that uniquely identifies a place as within Google Maps.
【Python|Python 小项目2 使用JSON API并处理数据】这里是存为文本,然后提取资料。

import urllib.request, urllib.parse, urllib.error import jsonfh = open('urlgeo.txt', 'w')# Note that Google is increasingly requiring keys # for this API, recheve the information from the website serviceurl = 'http://py4e-data.dr-chuck.net/geojson?'while True: address = input('Enter location: ') #address = 'University of Buenos Aires' if len(address) < 1: breakurl = serviceurl + urllib.parse.urlencode( {'address': address})print('Retrieving', url) uh = urllib.request.urlopen(url) data = https://www.it610.com/article/uh.read().decode() print('Retrieved', len(data), 'characters')try: js = json.loads(data) except: js = Noneif not js or 'status' not in js or js['status'] != 'OK': print('==== Failure To Retrieve ====') print(data) continueraw_data = https://www.it610.com/article/json.dumps(js, indent=4) fh.write(raw_data+'\n') fh.close()# load the file information into data fh = open('urlgeo-1.txt') data = https://www.it610.com/article/fh.read() fh.close()# extract the inforamtion from Json raw_handle = json.loads(data) # print(len(raw_handle)), two keys are status and results handle_results = raw_handle['results']#print(type(handle_results),len(handle_results)), #this is a list with only one valuehandle_address = handle_results[0] place_id = handle_address['place_id'] print(place_id)

    推荐阅读