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.

这里是存为文本,然后提取资料。

import urllib.request, urllib.parse, urllib.error
import json

fh = 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: break

    url = serviceurl + urllib.parse.urlencode(
        {'address': address})

    print('Retrieving', url)
    uh = urllib.request.urlopen(url)
    data = uh.read().decode()
    print('Retrieved', len(data), 'characters')

    try:
        js = json.loads(data)
    except:
        js = None

    if not js or 'status' not in js or js['status'] != 'OK':
        print('==== Failure To Retrieve ====')
        print(data)
        continue

    raw_data = json.dumps(js, indent=4)
    fh.write(raw_data+'\n')
    fh.close()

    # load the file information into data
    fh = open('urlgeo-1.txt')
    data = 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 value

    handle_address = handle_results[0]
    place_id = handle_address['place_id']
    print(place_id)

你可能感兴趣的:(Python 小项目2 使用JSON API并处理数据)