我如何从保存为文本文件的文件中获取平均值

时间:2015-09-15 17:40:35

标签: python

我必须以以下形式从文本文件中获取信息:

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("0123456789")


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

这就是我所拥有的一切,我被困住了。

1 个答案:

答案 0 :(得分: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. for循环完成,然后进行数学运算以找到平均值

    average = running_total / num_scores
    
  8. 您可以通过列表理解的魔力结合其中的一些步骤来提出更简洁的内容,如下所示:

    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)