首页 > 解决方案 > 转换接受 .txt 文件的程序并修改为函数

问题描述

完全卡在功能上......

我有一个 .txt 文件:

Bronson 90 85 75 76 
Conor 90 90 90 90
Austyn 50 55 32 75
Mark 96 95 85 85
Anthony 85 85 85 85 

我正在尝试使用此代码(如下)。并将其转换为产生相同输出的函数:

with open(argv[1]) as f:
     names = []
     for line in f:
        names.append(line.split()[0])
        print('\nNames of students who have written tests:')
        print(*sorted(names), sep=' ')

# prompt user to input which student you want to view
      name = input('Enter name of student whose test results '
                     'you wish to see: ')
      if name not in names:
          print('\nNo test data found for ', name)
          input("Press Enter to continue ...")
      else:
          name_print = "\nSummary of Test Results for " + name

# print test scores of the student selected
      with open(argv[1]) as f:
          for line in f:
              parts = line.split()
              if parts[0] == name:
                  print(name_print)
                  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
===================================
Test scores:  85 85 85 85
Number of tests written ..................  4

我想让它在一个 main() 模块上运行,使用process_marks(f)

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). #The program essentially runs in this function with help from helpers
    f.close()

main()

这是我目前拥有的:

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

def check_name(name, names):
    if name not in names:
        print('\nNo test data found for ', name)
        input("Press Enter to continue ...")
    else:
        name_print = "\nSummary of Test Results for " + name
        print(name_print)
        print('=' * ((len(name_print)) - 1))

def print_grades(name, line):
    test_scores = ' '.join(line[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: Mark

Summary of Test Results for Mark
================================
Test scores:  n t h o n y   8 5   8 5   8 5   8 5

我不想远离我拥有的当前代码(我想使用列表等,因为 id 最终喜欢包括平均值、最大值、最小值等。但是,我已经研究了一段时间有明显的问题获取代码以访问与名称对应的行。

标签: pythonfunction

解决方案


你的方法分解有点不对劲。

例如这一行:

print_grades(name, line)

line将使用上面 for 循环中的最后一个值。这将永远是"Anthony"

您可以尝试将值从方法传递到方法,如下所示:

from sys import argv


def get_names(my_file):
    names = []
    for line in my_file:
        names.append(line.split()[0])
        print('\nNames of students who have written tests:')
        print(*sorted(names), sep=' ')
    return names


def get_and_check_name(names):
    name = input('Enter name of student whose test results '
                 'you wish to see: ')
    if name not in names:
        print('\nNo test data found for ', name)
        input("Press Enter to continue ...")
    else:
        name_print = "\nSummary of Test Results for " + name
        return name, name_print


def print_scores(f, name, name_print):
    for line in f:
        parts = line.split()
        if parts[0] == name:
            print(name_print)
            print('=' * ((len(name_print)) - 1))
            test_scores = ' '.join(parts[1:])
            print('Test scores: ', end=' ')
            print(test_scores)


def process_marks(f):
    While True:
        names = get_names(f)
        name, name_print = get_and_check_name(names)
        f.seek(0)
        print_scores(f, name, name_print)
        yes_no = input('\nDo again for another student?')
        if yes_no == 'n':
            break
        continue 

with open(argv[1]) as f:
    process_marks(f)

推荐阅读