用于计算来自一组商标

时间:2018-02-17 16:26:01

标签: python python-3.x csv

我有一个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%。

2 个答案:

答案 0 :(得分:0)

此类任务适用于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)

答案 1 :(得分:0)

以下是仅使用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