【问题标题】:CSV file for calculating passing of failing grade from a set of marksCSV 文件,用于根据一组分数计算及格分数
【发布时间】:2018-02-17 16:26:00
【问题描述】:

我有一个 CSV 文件,其当前格式如下。

这样的两行示例是:

first_Name  last_Name   test1   test2   test3   test4
Alex        Brian       11      17      13      24
Pete        Tong        19      14      12      30

现在我当前的代码不起作用,简单地说我不确定我是否在正确的轨道上。 我当前的代码:

def grader(test1, test2, test3, finalExam):
    first = test1 * .20
    second = test2 * .20
    third = test3 * .20
    fourth = finalExam *.40
    finalGrade = first + second + third + fourth
    return finalGrade

def gradeScores(FinalGrade):
    if FinalGrade >= 90 and FinalGrade <= 100:
        return("You received an A")

    elif FinalGrade >= 80 and FinalGrade < 90:
        return("You received a B")

    elif FinalGrade >= 70 and FinalGrade < 80:
        return("You received a C")

    elif FinalGrade >= 60 and FinalGrade < 70:
        return("You received a D")

    else:
        return("Sorry, you received an F")

我也有这行代码用来读取 CSV 文件,并显示在输出窗口中。

with open("studentGradeFrom.csv") as csvfile:
    readFile = csv.reader(csvfile, delimiter=",", quotechar="¦")
    for row in readFile:
        print(row)

但是,由于我是 Python 新手,我正在寻求帮助来创建一个 Python 脚本,该脚本将查看结果并进行计算,从而告诉我学生是否通过或失败。 我希望这在一个单独的文件中完成。所以我猜我需要读取和写入不同的 CSV 文件,以显示学生是否失败或总体通过率。

with open("studentGradeTo.csv", 'w') as avg: #used to write to after the calculation is complete
    loadeddata = open("studentGradeFrom.csv", 'r') #used to read the data from the CSV before calculation.
    writer=csv.writer(avg)
    readloaded=csv.reader(loadeddata)
    listloaded=list(readloaded)

现在我的问题是:我将如何做这件事,从一个包含大约 50 个不同学生的文件中查看数据。虽然不使用学生成绩更改读取的 CSV,但仅更改显示通过或不及格成绩的 CSV 文件。任何帮助将不胜感激。

编辑:我忘了提到第一次测试将是最终成绩的 20%,与第二次和第三次测试相同。这三项合计占期末成绩的 60%。而第四次测试的价值占期末成绩的 40%。

【问题讨论】:

  • 您希望输出文件究竟是什么样的?学生姓名和“你的成绩是 F”在不同的列中?
  • 另外,考虑为此使用pandas 库,这将允许您在大约 5 行代码中灵活地完成此操作。 pd.cut 将使分级分类变得容易
  • @BradSolomon 这是正确的。简单他们的名字,如果他们通过了,哪个等级。如果他们失败了,那么他们就会收到一个 F。
  • 除了导入 csv 之外,有没有其他方法可以在没有任何其他模块的情况下做到这一点?

标签: python python-3.x csv


【解决方案1】:

这是一个仅使用 csv 库的概念的快速示例(您当然可以对其进行很多优化,但它应该适用于该示例)。

import csv

student_grades = []

# First open up your file containing the raw student grades
with open("studentGradeFrom.csv", "r") as file:
    # Setup your reader with whatever your settings actually are
    csv_file = csv.DictReader(file, delimiter=",", quotechar='"')

    # Cycle through each row of the csv file
    for row in csv_file:
        # Calculate the numerical grade of the student
        grade = grader(
            int(row["test1"]),
            int(row["test2"]),
            int(row["test3"]),
            int(row["test4"])
        )

        # Calculate the letter score for the student
        score = gradeScores(grade)

        # Assemble all the data into a dictionary
        # Only need to save fields you need in the final output
        student_grades.append({
            "first_name": row["first_name"],
            "last_name": row["last_name"],
            "test1": row["test1"],
            "test2": row["test2"],
            "test3": row["test3"],
            "test4": row["test4"],
            "grade": grade,
            "score": score
        })

# Open up a new csv file to save all the grades
with open("studentGradeFrom.csv", "w", newline="") as file:
    # List of column names to use as a header for the file
    # These will be used to match the dictionary keys set above
    # Only need to list the fields you saved above
    column_names = [
        "first_name", "last_name", "test1", "test2", "test3",
        "test4", "grade", "score"
    ]

    # Create the csv writer, using the above headers
    csv_file = csv.DictWriter(file, column_names)

    # Write the header
    csv_file.writeheader()

    # Write each dictionary to the csv file
    for student in student_grades:
        csv_file.writerow(student)

您需要根据您的确切要求对其进行微调,但希望它能让您朝着正确的方向前进。如果您需要具体的参考,大部分内容都记录在官方文档中:https://docs.python.org/3.6/library/csv.html

【讨论】:

    【解决方案2】:

    这种任务适合pandas 库。

    这是一种解决方案,可在您的需求发生变化时进行调整。

    import pandas as pd
    
    df = pd.read_csv('studentGradeFrom.csv')
    
    #   first_Name last_Name  test1  test2  test3  test4
    # 0       Alex     Brian     11     17     13     24
    # 1       Pete      Tong     19     14     12     30
    
    boundaries = {(90, 100.01): 'A',
                  (80, 90): 'B',
                  (70, 80): 'C',
                  (60, 70): 'D',
                  (0, 60): 'F'}
    
    def grade_calc(x, b):
        return next((v for k, v in b.items() if k[0] <= x <= k[1]), None)
    
    df['FinalMark'] = 0.2*df['test1'] + 0.2*df['test2'] + 0.2*df['test3'] + 0.4*df['test4']
    df['FinalGrade'] = df['FinalMark'].apply(grade_calc, b=boundaries)
    
    #   first_Name last_Name  test1  test2  test3  test4  FinalMark FinalGrade
    # 0       Alex     Brian     11     17     13     24       17.8          F
    # 1       Pete      Tong     19     14     12     30       21.0          F
    
    df.to_csv('studentGradeTo.csv', index=False)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-11
      • 1970-01-01
      • 1970-01-01
      • 2021-03-31
      • 1970-01-01
      相关资源
      最近更新 更多