标签:
question:
The program will prompt for a URL, read the JSON data from that URL using urllib and then parse and extract the comment counts from the JSON data, compute the sum of the numbers in the file.
Extracting Data from JSON
In this assignment you will write a Python program somewhat similar to http://www.pythonlearn.com/code/json2.py. The program will prompt for a URL, read the JSON data from that URL using urllib and then parse and extract the comment counts from the JSON data, compute the sum of the numbers in the file and enter the sum below:
We provide two files for this assignment. One is a sample file where we give you the sum for your testing and the other is the actual data you need to process for the assignment.
You do not need to save these files to your folder since your program will read the data directly from the URL. Note: Each student will have a distinct data url for the assignment - so only use your own data url for analysis. Data Format
The data consists of a number of names and comment counts in JSON as follows:
{ comments: [ { name: "Matthias" count: 97 }, { name: "Geomer" count: 97 } ... ] }
The closest sample code that shows how to parse JSON and extract a list is json2.py. You might also want to look at geoxml.py to see how to prompt for a URL and retrieve data from a URL.
Sample Execution
$ python solution.py Enter location: http://python-data.dr-chuck.net/comments_42.json Retrieving http://python-data.dr-chuck.net/comments_42.json Retrieved 2733 characters Count: 50 Sum: 2...
Turning in the Assignment
Python code:
My Code
1 import urllib 2 import json 3 4 # url = ‘http://python-data.dr-chuck.net/comments_265446.json‘ 5 while True: 6 address = raw_input(‘Enter location: ‘) 7 if len(address) < 1 : break 8 print ‘Retrieving‘, address 9 uh = urllib.urlopen(address) 10 data = uh.read() 11 print ‘Retrieved‘,len(data),‘characters‘ 12 input = urllib.urlopen(address).read() 13 js = json.loads(input) 14 sum = 0 15 for dict in js[‘comments‘]: 16 sum += int(dict[‘count‘]) 17 print ‘Total count:‘, len(js.get(‘comments‘,[])) 18 print ‘sum: ‘, sum 19 break
运行结果
学习心得:
1.count的长度不会使用,在stackoverflow上借鉴了len(js.get(‘comments‘,[])) 这个语句。
http://stackoverflow.com/questions/34807054/extracting-data-from-dictionary-in-python
2.整体代码学习源
1 import urllib 2 import json 3 4 url = ‘http://python-data.dr-chuck.net/comments_194528.json‘ 5 6 input = urllib.urlopen(url).read() 7 js = json.loads(input) 8 sum = 0 9 for dict in js[‘comments‘]: 10 sum += int(dict[‘count‘]) 11 print sum
http://www.cnblogs.com/wanderingzj/p/5010460.html
使用Python访问网络数据 python network-data 第六章
标签:
原文地址:http://www.cnblogs.com/Gailsunset/p/5596237.html