首页 > 解决方案 > 从txt读取分数并显示最高分数和记录

问题描述

从 Python第 6 章开始练习:

  1. 高分 假设计算机磁盘上存在一个名为 scores.txt 的文件。它包含一系列记录,每个记录有两个字段——一个名称,后跟一个分数(1 到 100 之间的整数)。编写一个程序,显示得分最高的记录的名称和得分,以及文件中的记录数。(提示:使用变量和“if”语句来跟踪您在阅读记录时找到的最高分数,并使用变量来记录记录的数量。)
Data in grades.txt
Jennifer 89
Pearson 90
Nancy 95
Gina 100
Harvey 98
Mike 99
Ross 15
Test 90

file=open('grades.txt','r')
my_list=[]

num_of_records=0
highest_score=1
highest_score_name=''

for line in file:
    name,score=line.strip().split()
    if int(score)>highest_score:
        highest_score=int(score)
        highest_score_name=name

    num_of_records=num_of_records+1


print('the name and score of the record with highest score:')
print('Name:',highest_score_name)
print('Score:',highest_score)

print('\nNumber of records:',num_of_records)

file.close()

在这里使用python的总入门并试图通过这本书但是在这个问题上遇到了错误。

错误:

line 9, in <module> name,score=line.strip().split() 
  ValueError: not enough values to unpack (expected 2, got 0)

任何指南表示赞赏。

标签: python

解决方案


好的,发生的事情实际上是您的数据在文件末尾有一个换行符,当您尝试拆分时,它会导致错误。这是正确的代码:

file = open('grades.txt', 'r')

num_of_records = 0
highest_score = 1
highest_score_name = ''

for line in file:
    line = line.strip()
    # Check whether the line is empty
    if line == '':
        continue

    name, score = line.split()
    if int(score) > highest_score:
        highest_score = int(score)
        highest_score_name = name

    num_of_records = num_of_records+1


print('the name and score of the record with highest score:')
print('Name:', highest_score_name)
print('Score:', highest_score)

print('\nNumber of records:', num_of_records)

file.close()

希望对你有帮助:)


推荐阅读