【问题标题】:Reading a .txt file and sorting into categories Python 3读取 .txt 文件并分类 Python 3
【发布时间】:2014-02-24 14:00:32
【问题描述】:

我正在尝试访问存储在文本文件中的数据并按文本文件中的特定行对数据进行排序。

这是数据," " 中的文本不包含在文本文件中,仅供参考:

741258 "This is a student ID" 
CSF105 "This is a course module"
39 "This is a module mark"
CSF104
86
CSF102
71
CSF106
16
CSF103
3
CSF100
88
CSF101
50
123456
CSF100
50
CSF101
98
CSF102
74
CSF103
84
CSF104
65
CSF105
79
CSF106
100

我需要提取学生 ID,然后根据该学生 ID 构建模块和分数列表并生成该学生的平均分数,我正在使用类和方法对数据进行排序,如果我直接通过函数只使用一组数据,即

id1 = Student("754412")
id1.addMark(Mark("CSF102", 90))
id1.addMark(Mark("CSF101", 80))
id1.addMark(Mark("CSF101", 42))
id1.addMark(Mark("CSF104", 90))
print(id1)
print("The Students average mark is: ", id1.calculateAverageMark())

它有效。如何让 python 读取这些行并确定列表中的下一个学生 ID,以便在学生的最后一个标记/模块之后不连续读取?我希望这是有道理的。

【问题讨论】:

  • 大概CSF 标记了课程线?例如。在课程标记之后,当一行不以CSF 开头时,有一个新学生?

标签: python list class python-3.x file-io


【解决方案1】:

只需循环打开文件对象并使用next() 在循环中获取下一行以读取课程和课程标记。

如果一行不以CSF 开头,则假设我们开始阅读一个新学生:

with open(inputfilename) as infh:
    student = Student(next(infh).strip())
    # auto-strip all lines
    infh = (l.strip() for l in infh)
    for line in infh:
        if line.startswith('CSF'):
            student.addMark(Mark(line, next(infh)))
        else:
            # new student, output information on the previous student first
            print(student)
            print("The Students average mark is: ", student.calculateAverageMark())
            student = Student(line)

    # last student info
    print(student)
    print("The Students average mark is: ", student.calculateAverageMark())

【讨论】:

  • fileinfh 更具可读性。为了避免重复.strip()lines = (line.strip() for line in file)
  • @J.F.Sebastian: file 掩盖了内置类型对象,当您打开另一个(可写)文件时,infhoutfh 是可区分的。
  • open;在大多数情况下,您不应该直接使用file。我在您的示例中没有看到第二个文件。在这种情况下,我使用input_fileoutput_file
  • @J.F.Sebastian:isinstance() 仅适用于 file,不适用于 open
  • file very 在 Python 2 中很少需要。它在 Python 3 中消失了。OP 使用 Python 3。总的来说,我同意你不应该影子内置,但在这种特殊情况下 (file),这是应该打破的规则。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-13
  • 1970-01-01
  • 2016-10-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多