Advertisement
Guest User

Untitled

a guest
Apr 17th, 2014
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. """
  2. Troy Goda - inclass9.py
  3. Algorithm
  4. Define function called makeAverage(student,key):
  5. take student[key] and store as scores
  6. Set total to 0
  7. for score in scores:
  8. set total = total + score
  9. take total and divide by length of scores, store as average
  10. return average
  11. import json
  12. Ask user to enter name of JSON file to process, store handle as filename and strip whitespace + \
  13. and force to lowercase letters
  14. open filename for reading, store handle as infile
  15. use json.loadstring, read all lines in infile, and store in list called mydictionary
  16. take ["students"] key of mydictionary, store as studentsList
  17. for student in studentsList:
  18. print student["name"] + "," + " hw average: " + str(makeAverage(student,"hwscores")) + "," + \
  19. + " exam average: " + str(makeAverage(student,"exams"))
  20. 1)
  21. One reason that JSON files are better than CSV is because JSON files are processed much more easily
  22. and efficiently than CSV. For this assignment, a CSV file would have 7 different data separated by
  23. commas,and you either need to label each score, or you might not process the data correctly. You would
  24. have to split the list and then identify which tokens goes to name, every hwscores, and every exam score.
  25. This is much slower than using a JSON file where you can just take the keys "name", "hwscores","exams",
  26. and automatically get the data you want. You also need to convert all of the hwscores and exam scores
  27. to a number, because in a CSV file list they are strings. Another reason is that you can have a
  28. hierarchy data, like an XML, but in a much easier and simpler form to process and read the file.
  29.  
  30. Jane Doe,85.1,95.0,95.0,92.7,91.4,95.2
  31. John Doe,95.1,90.5,90.1,91.1,81.3,85.6
  32. Bill Gates,60,60,75,98.7,94.4,96.4
  33.  
  34. """
  35. def makeAverage(student,key):
  36. scores = student[key]
  37. total = 0
  38. for score in scores:
  39. total += score
  40. average = total / len(scores)
  41. return average
  42. import json
  43. filename = raw_input("Enter name of JSON file to process: ").strip().lower()
  44. #filename = "studentscores.json"
  45. infile = open(filename,"r")
  46. mydictionary = json.loads(infile.read())
  47. studentsList = mydictionary["students"]
  48. for student in studentsList:
  49. print student["name"] + "," + " hw average: " + str(makeAverage(student,"hwscores")) + "," + \
  50. + " exam average: " + str(makeAverage(student,"exams"))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement