2017-06-29 136 views
0

修改:計算環蟒蛇得分文件

用下面的學生的分數文件,我將如何加載數據,並在Python總結score1score3

{"id": "1","student":"John", "dt": "1997-01-01 07:00:02", "score1": "38.28"} 
{"id": "2", "student":"Jane", "dt": "1997-01-01 07:00:02", "score1": "32.35"} 
{"id": "3", "student":"Richard", "dt": "1997-01-10 10:00:00", "score3": "22.92"} 

輸出:

score1: 70.63 
score3: 22.92 
+0

到目前爲止您嘗試了什麼? –

+0

有很多方法可以解決這個問題,你需要一個非常具體的實現,試着問一個更加尖銳的問題,比如「如何將文本文件讀入python」(儘管它已經有了答案:https: //stackoverflow.com/questions/14676265/how-to-read-text-file-into-a-list-or-array-with-python#14676357)。你希望他們如何閱讀?只是分數還是你想要所有的數據?你對格式有什麼瞭解? –

+2

顯然通過調用'get_stackoverflow_to_do_all_my_homework()' – donkopotamus

回答

0

file.txt的

{"id": "1","student":"John", "dt": "1997-01-01 07:00:02", "score1": "38.28"} 
{"id": "2", "student":"Jane", "dt": "1997-01-01 07:00:02", "score1": "32.35"} 
{"id": "3", "student":"Richard", "dt": "1997-01-10 10:00:00", "score3": "22.92"} 

務必:

import json 

scores = dict() 
with open('file.txt') as filename: 
    for line in filename.readlines(): 
     data = json.loads(line) 
     score = [key for key in data.keys() if key.startswith('score')] 
     if len(score) == 0: 
      continue 
     score = score[0] 
     if score not in scores: 
      scores[score] = 0 
     scores[score] += float(data[score]) 

for k, v in scores.items(): 
    print('{}: {}'.format(k, v)) 

輸出繼電器:

score1: 70.63 
score3: 22.92 
0

使用內置庫json您可以將JSON解碼爲Python對象。 如果使用這樣的數據:

[ 
    {"id": "1","student":"John", "dt": "1997-01-01 07:00:02", "score1": "38.28"}, 
    {"id": "2", "student":"Jane", "dt": "1997-01-01 07:00:02", "score1": "32.35"}, 
    {"id": "3", "student":"Richard", "dt": "1997-01-10 10:00:00", "score3": "22.92"} 
] 

注中的數據[...],所以它加載的列表。

然後下面的腳本可以完成這項工作。

import json 
from math import fsum 

data = json.load(open("data.json")) # Load the data 
sums = {} 
for person in data: # Loop over pieces of data 
    # Add any names starting with "score" to sums 
    for key in person.keys(): # Loop over names 
     if not key[:5] == "score": 
      continue # No, not starting with score, skip it 
     # Use math.fsum to add the value known to the score, and set it. 
     sums[key] = fsum([sums.get(key, 0.0), float(person[key])]) 
for k, v in sums.items(): 
    # Print out the data 
    print("%s: %.02f" % (k, v)) 

我在評論中添加了解釋。在IDLE 3.6.1中測試。