如何使用python解析此类文件?

2024-05-13 07:54:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我对编程和Python还不熟悉,我正在努力完成我的任务。 任务:

''文件行存储学生姓名及其平均成绩,用空格分隔(例如“John 9.5”)。该程序对学生的平均成绩进行四舍五入,并相应地将学生分成组(平均成绩为10、9、8、7等的学生)并写入不同的文件。使用函数式编程“

该文件如下所示:

John 9.5
Anna 7.8
Luke 8.1

我不知道如何只取数字并将其四舍五入,然后如何使名称和数字成为一个元素,并根据其等级将其放入不同的文件中

我试过:

f = open('file.txt')
sar = []
sar = f.read().split()
print(sar)
d = sar[::2]
p = sar[1::2]
print(p)

p = [round(float(el)) for el in p]
print(p)

f.close()

这是:

f = open('duomenys.txt')
lines = [line.rstrip('\n') for line in f]
print(lines)

        
f.close()

Tags: 文件intxtforclose编程数字open
1条回答
网友
1楼 · 发布于 2024-05-13 07:54:52

所以,通过你的问题,我理解你只需要根据学生的平均数对文件中的数据进行排序,然后将它们放在不同的文件中。为了实现这个目标,我想你可以用这个

def sorting():
    infile = open("file.txt", 'r')
    data = infile.read().splitlines()
    for item in data:
        item = item.split(' ')
        item[1] = round(float(item[1]))
        print(item)
        placing(item[0], item[1])


def placing(name, grade): #to place the students in sorted files
    if grade == 10:
        infile = open('10.txt', 'a')
        infile.write(f"{name} {grade}")
    elif grade == 9:
        infile = open('9.txt', 'a')
        infile.write(f"{name} {grade} \n") #further you can create more files.


sorting()

相关问题 更多 >