【发布时间】:2019-04-11 19:36:22
【问题描述】:
我遇到的问题是,当程序读取文件时,它正在读取名称以及必要的数字,但我无法将数字转换为浮点数。文本文件称为“gym.txt”,这就是我必须阅读的内容。我在一个低级编码类,所以代码应该有点基本。以下是“gym.txt”的内容:
5
Albert 9.2 9.3 9.0 9.9 9.5 9.5 9.6 9.8
John 9.1 9.4 9.6 9.8 9.4 9.3 9.9 9.1
Jay 9.2 9.3 9.0 9.9 9.4 9.3 9.9 9.1
Henry 9.4 9.3 9.9 9.1 9.5 9.5 9.6 9.8
Walter 9.2 9.3 9.4 9.3 9.9 9.1 9.6 9.0
5 表示参赛者的数量,在这些分数中,每个人的最高和最低被丢弃。然后总数变为 6,并且不包括每个人的最低和最高分数。
我已尝试逐行读取文件,如下面的代码所示,但由于名称与数字在同一行,将其转换为浮点数失败。如果可行,我计划为每个名称和分数集执行此代码。
f=open('gym.txt','r')
judges=6
contestants=f.readline().rstrip("\n")
print(contestants)
albert=str(f.readline().rstrip('\n'))
albert_list=float(albert.strip("Albert"))
print(albert_list)
预期的结果是以下输出:
The number of contestants is 5.
Contestant Scores
_______________________________________________
Albert 9.3 9.0 9.9 9.5 9.5 9.6 9.8
John 9.4 9.6 9.8 9.4 9.3 9.9 9.1
Jay 9.3 9.0 9.9 9.4 9.3 9.9 9.1
Henry 9.3 9.9 9.1 9.5 9.5 9.6 9.8
Walter 9.3 9.4 9.3 9.9 9.1 9.6 9.0
Total score of Albert is 9.48.
Total score of John is 9.43.
Total score of Jay is 9.37.
Total score of Henry is 9.52.
Total score of Walter is 9.32.
The highest total score amongst the contestants is 9.52.
The lowest total score amongst the contestants is 9.32.
格式化对我来说不是一个大问题,我只是对程序本身的帮助感兴趣。这是我得到的错误:
5
Traceback (most recent call last):
File "C:/Users/theon/PycharmProjects/untitled/CS 1113/gymnasium.py", line 6, in <module>
albert_list=float(albert.strip("Albert"))
ValueError: could not convert string to float: ' 9.2 9.3 9.0 9.9 9.5 9.5 9.6 9.8'
【问题讨论】:
标签: python-3.x