如何使用split()分隔和显示文本文件来计算和平均

时间:2017-07-20 01:18:51

标签: python split

我遇到split()功能问题。我有一个名为printReport()的模块,其中包含一个名称,每行有3个测试分数。我需要拆分数据,以便显示名称和分数并计算平均值。我很肯定我试图完全错误。我得到了IndexError: list index out of range.这只是我问题的开始。我仍然不知道如何进行计算并显示如下。

        

学生姓名得1分2得分3总

           

Dave 82 91 77 250

     

Tom 79 22 84 185

     

迪克67 22 91 180

           

2016年2月8日星期一15:12:08

有人可以解释一下我做错了什么以及如何解决它。

    ### Subprogram detStudentData(fn, scores)

    def getStudentData(fn, scores):
        #   Writes instructions for the user to follow
        print("Enter the student names and scores following the prompts below.")
        print("To finish entering student names, enter: ZZZ.\n")

        #   Set the flag for the loop
        done = False
        #   Loop to get input from the usere
        while done != True:

            #   Creates a newFile and enables append
            newFile = open(fn, "a")
            #   Asks for a student name and assigns it to student_name
            student_name = input("Please enter the student name (ZZZ to finish): ")
            #   Compairs student_name to see if it is equal to "ZZZ"
            if student_name == "ZZZ":
                #   Sets the flag to True to exit the loop
                done = True
            #   Asks for test scores if student_name is not equal "ZZZ"
            else:
                #   Asks for test score 1 and assigns it to test_1
                test_1 = input("Enter score 1: ")
                #   Asks for test score 2 and assigns it to test_2
                test_2 = input("Enter score 2: ")
                #   Asks for test score 3 and assigns it to test_3
                test_3 = input("Enter score 3: ")
                print("\n")

                newFile.write(student_name) #  Writes student_name to newFile
                newFile.write(", ")         #  Writes "," to newFile
                newFile.write(test_1)       #  Writes test_1 to newFile
                newFile.write(", ")         #  Writes "," to newFile
                newFile.write(test_2)       #  Writes test_2e to newFile
                newFile.write(", ")         #  Writes "," to newFile
                newFile.write(test_3)       #  Writes test_3 to newFile
                newFile.write("\n")         #  Wites a return to newFile

            #   Closes newFile
            newFile.close()
    # ==============================================================================

    ### Subprogram getTextFileContents(fn)

    def getTextFileContents(fn):
        #   Opens the file and enables read
        with open(fn, "r") as ins:
            #   Splits the text file before the ","
            list = fn.split(",")

            #   Creates a loop to load the characters into a list
            for line in ins:
                #   Appends the text to list
                list.append(line)

        # Returns the value in list
        return list


    # ==============================================================================

    ### Subprogram printReport(line)

    def printReport(line):
        #   Prints the heading to show the test scores
        print("__________________________________________________________")
        print("Student Name     Score 1     Score 2     Score 3     Total")
        print("----------------------------------------------------------")

        name = []       #   Declare name a list
        test1 = []      #   Declare test1 a list
        test2 = []      #   Declare test2 a list
        test3 = []      #   Declare test a list

        with open("grades.txt", "r") as f:
            for line in f:
                name.append(line.split(",", 1)[0])
            line = name[0]
            capacity = len(name)
            index = 0
            while index != capacity:
                line = name[index]
                for nameOut in line.split():
                    print(nameOut)
                    index = index + 1

        # ================================================

        with open("grades.txt", "r") as f:
            for line in f:
                test1.append(line.split(",", -1)[1])
            line = test1[1]
            capacity = len(test1)
            index1 = 0
            while index1 != capacity:
                line = test1[index1]
                for t1Out in line.split():
                    print(t1Out)
                    index1 = index1 + 1

        # ================================================

        with open("grades.txt", "r") as f:
            for line in f:
                test2.append(line.split(",", -1)[2])
            line = test2[2]
            capacity = len(test2)
            index2 = 0
            while index2 != capacity:
                line = test2[index2]
                for t2Out in line.split():
                    print(t2Out)
                    index2 = index2 + 1

        # ================================================

        with open("grades.txt", "r") as f:
            for line in f:
                test3.append(line.split(" ", -1)[3])
            line = test3[3]
            capacity = len(test3)
            index3 = 0
            while index != capacity:
                line = test3[index3]
                for t3Out in line.split():
                    print(t3Out)
                    index3 = index3 + 1

    # ==============================================================================
    def main():


        fn = "grades.txt"               #   set the working file name
        scores = 3                      #   set the number of scores
        getStudentData(fn, scores)      #   Calls getStudentData()
        line = getTextFileContents(fn)  #   Assigns getTextFileContent() to line
        printReport(line)               #   Calls printReport()

    main()

2 个答案:

答案 0 :(得分:1)

检查线

line = test1[1]
line = test2[2]
line = test3[3]

您应该从0开始,而不是123

答案 1 :(得分:0)

违规部分是:

        while index != capacity:
            line = test3[index3]
            for t3Out in line.split():
                print(t3Out)
                index3 = index3 + 1

第一行应该是:

while index3 != capacity:

请注意,手动递增索引可能不是在Python中循环遍历列表的最佳方法。更加pythonic的方式可能是:

for item in test3:
    for t3out in item.split():
         print(t3out)

此外,如果您要坚持手动递增,则需要从for循环中删除index = index + 1。您应该只在处理每一行后递增。

        while index != capacity:
            line = test3[index3]
            for t3Out in line.split():
                print(t3Out)
            index3 = index3 + 1