创建一个功能来处理学生成绩的.txt文件 [英] Creating a function to process through a .txt file of student grades

查看:105
本文介绍了创建一个功能来处理学生成绩的.txt文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮忙...

我的驱动程序文件在这里:

My driver file is here:

from functions import process_marks 

def main():
    try:
        f = open(argv[1])
    except FileNotFoundError:
        print("\nFile ", argv[1], "is not available")
        exit()
    process_marks(f)
    f.close()

main()

我正在尝试修改 process_marks(f)以运行我的代码.并生成此文件(从没有功能的文件运行):

I'm trying to modify process_marks(f) to run my code. and produce this (from file that runs without functions):

Names of students who have written tests:
Anthony Austyn Bronson Conor Mark
Enter name of student whose test results you wish to see: Anthony

Summary of Test Results for Anthony
===================================
Test scores:  85 85 85 85
Number of tests written ..................  4

这是我目前拥有的:

names = []
name_print = "\nSummary of Test Results for "

def process_marks(file_name):
    names
    for line in file_name:
        names.append(line.split()[0])
    print('\nNames of students who have written tests:')
    print(*sorted(names), sep=' ')
    name = input('Enter name of student whose test results '
            'you wish to see: ')
    check_name(name)
    parts = line.split()
    if parts[0] == name:
        print_scores(name)



def check_name(person):
    if person not in names:
        print('\nNo test data found for ', person)
        input("Press Enter to continue ...")
    else:
        print(name_print + person)        


def print_scores(person, parts):
        print('=' * ((len(name_print)) - 1))
        test_scores = ' '.join(parts[1:])
        print('Test scores: ', end=' ')
        print(test_scores)

哪个输出:

Names of students who have written tests:
Anthony Austyn Bronson Conor Mark
Enter name of student whose test results you wish to see: Anthony

Summary of Test Results for Anthony

我需要帮助使 print_scores()函数在 process_marks()中起作用.

I need help making print_scores() function work in process_marks().

有人可以看到我的错误所在吗?

Can someone see where my errors lie?

推荐答案

您的错误(主要是)您将输入名称与文件的最后一行进行了比较.这是因为您检查 parts [0] == name ,其中 parts = line.split().这意味着 parts 始终位于文件的 last 行中-无论提供什么名称.

Your error (mainly) lies in the fact that you are comparing the input name to the last row of the file. This is because you check if parts[0] == name where parts = line.split(). This means the parts are of the last row of the file always - no matter what name provided.

要解决此问题,我将从存储数据的更好方法开始.现在,您只是将名称保存在列表中.但是成绩呢?我认为更好的解决方案是使用 dict .因此,请先更改为:

To fix this, I would start by a better way of storing your data. Right now you are just saving the names in a list. But what about the grades? I think a better solution would be to use a dict. So start by changing to:

names = {}  # instead of []

现在,您要使用名称作为键来填充该字典(保留与列表类似的逻辑),并将等级列表作为该键的值.因此,您的文件解析可能类似于:

Now you want to fill that dict with the names as keys (keeps the logic similar as with the list) and the list of grades as the value for that key. So your file parsing can look like:

for line in file_name:
    elements = line.split()
    names[elements[0]] = elements[1:]
# names now look like: {'Anthony': ['85', '85', '85', '85'], 'Conor': [...], ... }


现在另一件事是,您调用 check_name 函数,然后在 process_marks 中进行另一次检查.这似乎是多余的.我将更改 ceck_name 函数以返回一个布尔值,指示名称是否正确:


Now another thing is that you call the check_name function but then make another check in process_marks. This seems redundant. I would change the ceck_name function to return a boolean indicating if the name is ok or not:

def check_name(person):
    if person not in names:
        print('\nNo test data found for ', person)
        input("Press Enter to continue ...")
        return False
    else:
        print(name_print + person)
        return True

process_marks 中,您可以将其用作:

And in process_marks you can use it as:

name = input('Enter name of student whose test results you wish to see: ')
if check_name(name):
    print_scores(name)


最后,关于 parts 问题.现在,您已经将成绩和它们所属的匹配名称一起存储在 names 中.因此,我们要做的就是将 print_scores 更改为仅接受一个参数 grade ,并使用它代替 parts ,并使用 process_marks只需调用它即可:


Lastly, regarding the parts issue. Now you have the grades stored in names along with the matching name they belong to. So all we have left to do is change print_scores to take only one argument grades and use that instead of parts, and from process_marks just call it:

print_scores(names[name])


可能的完整代码视图:


A view of a possible complete code:

names = {}
name_print = "\nSummary of Test Results for "

def process_marks(file_name):
    with open(file_name) as f:
        for line in f:
            elements = line.split()
            names[elements[0]] = elements[1:]
    print(names)
    print('\nNames of students who have written tests:')
    print(*sorted(names), sep=' ')
    name = input('Enter name of student whose test results you wish to see: ')
    if check_name(name):
        print_scores(names[name])

def check_name(person):
    if person not in names:
        print('\nNo test data found for ', person)
        input("Press Enter to continue ...")
        return False
    else:
        print(name_print + person)
        return True

def print_scores(grades):
    print('=' * (len(name_print) - 1))
    test_scores = ' '.join(grades)
    print('Test scores: ', end=' ')
    print(test_scores)

这篇关于创建一个功能来处理学生成绩的.txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆