Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- Troy Goda - inclass9.py
- Algorithm
- Define function called makeAverage(student,key):
- take student[key] and store as scores
- Set total to 0
- for score in scores:
- set total = total + score
- take total and divide by length of scores, store as average
- return average
- import json
- Ask user to enter name of JSON file to process, store handle as filename and strip whitespace + \
- and force to lowercase letters
- open filename for reading, store handle as infile
- use json.loadstring, read all lines in infile, and store in list called mydictionary
- take ["students"] key of mydictionary, store as studentsList
- for student in studentsList:
- print student["name"] + "," + " hw average: " + str(makeAverage(student,"hwscores")) + "," + \
- + " exam average: " + str(makeAverage(student,"exams"))
- 1)
- One reason that JSON files are better than CSV is because JSON files are processed much more easily
- and efficiently than CSV. For this assignment, a CSV file would have 7 different data separated by
- commas,and you either need to label each score, or you might not process the data correctly. You would
- have to split the list and then identify which tokens goes to name, every hwscores, and every exam score.
- This is much slower than using a JSON file where you can just take the keys "name", "hwscores","exams",
- and automatically get the data you want. You also need to convert all of the hwscores and exam scores
- to a number, because in a CSV file list they are strings. Another reason is that you can have a
- hierarchy data, like an XML, but in a much easier and simpler form to process and read the file.
- Jane Doe,85.1,95.0,95.0,92.7,91.4,95.2
- John Doe,95.1,90.5,90.1,91.1,81.3,85.6
- Bill Gates,60,60,75,98.7,94.4,96.4
- """
- def makeAverage(student,key):
- scores = student[key]
- total = 0
- for score in scores:
- total += score
- average = total / len(scores)
- return average
- import json
- filename = raw_input("Enter name of JSON file to process: ").strip().lower()
- #filename = "studentscores.json"
- infile = open(filename,"r")
- mydictionary = json.loads(infile.read())
- studentsList = mydictionary["students"]
- for student in studentsList:
- print student["name"] + "," + " hw average: " + str(makeAverage(student,"hwscores")) + "," + \
- + " exam average: " + str(makeAverage(student,"exams"))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement