gpt4 book ai didi

python - 从文本文件中提取数据

转载 作者:太空宇宙 更新时间:2023-11-04 01:32:04 25 4
gpt4 key购买 nike

我有以下输入:

ID,       Last,      First,   Lecture, Tutorial, A1,  A2, A3,   A4,  A5
10034567, Smith, Winston, L01, T03, 6, 5.5, 8, 10, 8.5
10045678, Lee, Bruce, L02, T05, 4.5, 6.5, 7, 7, 8.5
00305678, Obama, Jack, L01, T05, 10, 10, 9, 9.5, 10
00567890, Brown, Palin, L02, T03, 4, 7.5, 6.5, 0, 5
10012134, Harper, Ed, L01, T03, 10, 9, 7.5, 10, 6.5
10014549, Johnson, Andrew, L01, T05, 10, 0, 10, 5.5, 7
10020987, Clockwork, Milan, L02, T03, 10, 8.5, 8, 9, 9
10021234, Freeman, Skyski L01, T02, 0, 10, 10, 10, 8.5
EOF

文件的第一行解释了每一列数据。设 n 为学生总数,则文件的后 n 行每行对应类(class)中的一个学生,包含 10 个字段:

  1. 学号

  2. 姓氏

  3. 名字

  4. 讲座部分

  5. 教程部分

  6. 作业成绩 1 (依此类推...)

假设成绩存储在文件 grades.txt 中,那么您可以使用以下 Python 语句将文件的整行读入 Python 字符串 s:

file = open (‘grades.txt’, ‘r’)
s = file.readline()

你只需要打开文件一次,然后你可以多次使用readline()函数,每次读取连续的一行。在 n 行学生记录之后,文件以最后一行表示 EOFEnd of File 的缩写。

数字 n 是未知的优先级。示例输入无关紧要,它可以包含 100 到 300 名学生,在名为 grades.txt 的文件中。我们希望最终绘制作业 1 的成绩分布直方图。因此,您需要提取通过处理文件中他/她的相应行,为每个学生计算 A1 的成绩。构建一个列表,每个学生都有一个条目,存储他/她的 A1 成绩。每次提取新的 A1 成绩时,将其附加到此列表中。

到目前为止,这是我所做的:

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


for line in file:
newline = str(line)
grades = newline.split(",")
if len(grades)<=4:
break
elif len(grades)>5:
break
else:
grades = [float(x) for x in grades]
gradeA1 = grades[5]
print(gradeA1)

但是我只得到一年级 6 而不是任何连续行的其他 A1 等级,所有 A1 等级都应该编译成一个列表。

我将此作为我编辑的代码,但我仍然遇到错误。

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

for s in file:
s = file.readline()
grades = s.split(",")
if grades=='EOF\n':
break
A1grades = [float(x) for x in grades[5]]
print(A1grades)

我收到索引超出范围错误。

最佳答案

我认为问题可能是您没有读取文件中的所有行...也许你可以做这样的事情

firstLine = file.readline()
#extract from first line, the number of lines that next

for x in range(1,number_of_line)
line = file.readline()
#process the information for all next lines

这是一种实现方式,希望对你有帮助...

关于python - 从文本文件中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13296369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com