2015-09-15 33 views
-2

我不得不採取從文本文件信息的格式的文件得到的平均值:如何我可以從保存爲文本文件

Dom : 9 
Eathan : 0 
Harry : 8 
Jack : 7 
Jake : 0 
James : 1 
Jeffin : 1 
Louis : 8 
Sam : 0 
Tom : 3 
William : 0 

我需要從這個文本文件中把分數保存作爲int(因爲它們是字符串)並計算出平均值並打印出來。

import random 
import operator 

def randomCalc(): 
    ops = {'+':operator.add, 
      '-':operator.sub, 
      '*':operator.mul, 
      '/':operator.truediv} 
    num1 = random.randint(0,12) 
    num2 = random.randint(1,10) 
    op = random.choice(list(ops.keys())) 
    answer = ops.get(op)(num1,num2) 
    print('What is {} {} {}?\n'.format(num1, op, num2)) 
    return answer 

def askQuestion(): 
    answer = randomCalc() 
    while True: 
     try: 
     guess = float(input())#The Answer the user inputs to the question asked 
     except ValueError: #When anything but a interger is inputted. 
     print ("That is not a valid answer") 
     continue #Dosen't print Invalid Code Error 
     else: 
     break 
    return guess == answer 

def quiz(): 
    print('Welcome. This is a 10 question math quiz\n') 
    score = 0 
    for i in range(10): 
     correct = askQuestion() 
     if correct: 
      score += 1 
      print('Correct!\n') 
     else: 
      print('Incorrect!\n') 
    print ("\nYour score was {}/10 Well done".format(score)) 
    print ("\nWhat is your name") 
    name = str(input()) 
    class_name = input("\nWhich class do you wish to input results for? ") 
    class_name = class_name + ".dat" #adds '.txt' to the end of the file so it can be used to create a file under the name a user specifies 

    file = open(class_name, "a") #opens the file in 'append' mode so you don't delete all the information 
    name = (name) 
    file.write(str(name + " : ")) #writes the information to the file 
    file.write(str(score)) 
    file.write('\n') 
    file.close() 
    return score 

quiz() 

viewscore_alpha = str(input("\nWould you like to view the score`s of players alphabeticaly: Yes or No")) 
if viewscore_alpha == "yes".lower(): 
    class_name = input("\nWhich class do you wish to View results for? ") 
    class_name = class_name + ".dat" 
    with open(class_name) as file: # use with to open files as it closes them automatically 
     file.seek(0) # go back to start of file 
     for line in f: # print each name 
      print(line) 
     file.seek(0) # go back to start again 
     lines = sorted(file.readlines()) # sort the names 
     with open(class_name, "w") as file_save: # write names in sorted order 
      for line in lines: 
       file_save.write(line) 
     file.close() 
     file_save.close90 
elif viewscore_average == "no".lower() : 
    viewscore_average = str(input("\nWould you like to view the score`s of classes avrages?: Yes or No")) 
    if viewscore_average == "yes".lower(): 
     chars = set("") 


    else: 
     viewscore_higest = str(input("\nWould you like to view the score`s of players alphabeticaly: Yes or No")) 
     if viewscore_higest == "yes".lower(): 

這就是我所有的,我卡住了。

+0

請張貼代碼的其餘部分因爲我們無法猜測你做了什麼。 – wheaties

+0

是的,請張貼代碼。否則,它看起來像你要求我們爲你寫的代碼,這裏不允許使用。 此外,顯示您輸出*做*得到 - 至少一個阻塞語法錯誤。評論也將有所幫助,所以我們知道你設計了什麼(你正在努力做什麼)。 – Prune

+0

一開始,你應該嘗試移動'低()'函數您的變量,例如'viewscore_average.lower()'。 –

回答

0

將其分解爲邏輯步驟。

  1. 打開該文件(並初始化幾個變量,我們以後將使用)

    running_total = 0 
    num_scores = 0 
    with open("path/to/file.txt") as scoresfile: 
    
  2. 閱讀每一行

    for line in scoresfile: 
    
  3. 分裂冒號每一行

     splitline = line.split(":") 
    
  4. 分數轉換爲int

     score = int(splitline[1]) # splitline[1] is the score 
    
  5. 比分添加到運行總量

     running_total += score 
    
  6. 增量我們讀到的平均

     num_scores += 1 
    
  7. 劃分的行數
  8. for循環完成,然後做你的數學找到平均值

    average = running_total/num_scores 
    

您可以將其中的幾個步驟,通過列表理解的魔法拿出一些更簡潔,看起來像:

with open('path/to/file.txt') as scoresfile: 
    scores = [int(score) for line in scoresfile for 
       _, score in line.split(":")] 
average = sum(scores)/len(scores) 
+0

當你說分數= [int(得分)爲分數文件爲 _,得分在line.split(「:」)] –

+0

@BrianStrugnell你打開包裝有多少值(預計2)?消息可能是什麼 –

+0

這可能意味着在連續序列中運行2個不同的循環時出現問題我不能100%確定您能解釋@Adam Smith –

相關問題