【问题标题】:how to parse this kind of file using python?如何使用python解析这种文件?
【发布时间】:2021-04-26 11:14:51
【问题描述】:

我是编程和 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()

【问题讨论】:

  • 你会使用库吗?例如。熊猫?如果是这样,请尝试: df = pd.read_csv('file.txt')
  • 您的方法不使用函数式编程。你的代码中有副作用,但你不应该
  • @Andreas 我无法使用它,因为我还没有了解它

标签: python function file new-operator


【解决方案1】:

因此,根据您的问题,我了解到您只需要根据学生的平均成绩对文件中的数据进行排序,然后将它们放在不同的文件中。为了实现我认为你可以使用它。

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    相关资源
    最近更新 更多