如何使用python解析这种文件?
how to parse this kind of file using python?
我是编程新手,Python 我正在努力完成我的任务。
任务:
''The lines of the file store the names of the students and the average of their grades, separated by spaces (e.g."John 9.5"). The program rounds student averages and divides students accordingly into groups (students with an average of 10, 9, 8, 7, etc.) and write to different files.Use functional programming''
文件看起来像这样:
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()
根据你的问题,我了解到你只需要根据学生的平均值对文件中的数据进行排序,然后将它们放在不同的文件中。要实现我认为你可以使用这个。
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()
我是编程新手,Python 我正在努力完成我的任务。 任务:
''The lines of the file store the names of the students and the average of their grades, separated by spaces (e.g."John 9.5"). The program rounds student averages and divides students accordingly into groups (students with an average of 10, 9, 8, 7, etc.) and write to different files.Use functional programming''
文件看起来像这样:
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()
根据你的问题,我了解到你只需要根据学生的平均值对文件中的数据进行排序,然后将它们放在不同的文件中。要实现我认为你可以使用这个。
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()