注册服务商希望解析包含许多学生数据的文本文件。
输入文件:许多学生数据的文本文件(每个学生文件的格式相同)
我成功地找到了一个“模式”并将其打印到文件中,这是我需要的75%。在一种情况下,找到匹配项并打印了匹配行后,我需要打印下一行。 那就是我迷路的地方。 [可迭代,迭代器,生成器...对我来说都是希腊语]
文字示例:
Student............: StudentA
Program............: BA Adol Biology Education (ED.ADOL.BIO.BA)
C) 3: Lab Science Course
Complete 1 Lab Science course
CHM-111 General Chemistry I *4..... FA2018 A 4
I) 4: Adolescent Biology Education Major
Credits: 24
GPA Achieved/Needed: 4.000 / 2.500
Complete all 3 subrequirements:
I) A: Educ Requirements
COMPLETE 2 GROUPS
Credits: 5
GPA Achieved/Needed: none / 3.000
I) Group 1
Student............: StudentB
Program............: BA Adol Eng Education (ED.ADOL.ENG.BA)
C) 3: Lab Science Course
Complete 1 Lab Science course;
CHM-111 General Chemistry I *4..... FA2018 A 4
I) 4: Adolescent English Education Major
Credits: 24
GPA Achieved/Needed: 4.000 / 2.500
Complete all 3 subrequirements:
I) A: Educ Requirements
COMPLETE 2 GROUPS
Credits: 5
GPA Achieved/Needed: none / 3.000
I) Group 1
Student............: StudentC
Program............: BA Adol Chemistry Education (ED.ADOL.CHM.BA)
C) 3: Lab Science Course
Complete 1 Lab Science course;
CHM-111 General Chemistry I *4..... FA2018 A 4
I) 4: Adolescent Chemistry Education Major
Credits: 24
GPA Achieved/Needed: 4.000 / 2.500
Complete all 3 subrequirements:
I) A: Educ Requirements
COMPLETE 2 GROUPS
Credits: 5
运行Python 3.7.1;尝试过与__next__()
一起玩,但是没有成功。从我读过的print()
来看,将指针移到了下一行...所以我尝试这样做,但这不起作用。
outfile = open('result.txt', 'w')
with open('BEVL_EDU.txt','r') as inFile:
f = inFile.read().splitlines()
for line in f:
if 'Student...' in line:
outfile.write(line + '\n')
if '4:' in line:
outfile.write(line + '\n')
print(line) # --> this is where I tried to move the pointer to next line
outfile.write(line + '\n') # --> and then print the "next" line :-)
if 'GPA Achieved/Needed' in line:
outfile.write(line + '\n')
答案 0 :(得分:1)
首先应该做一些事情,以使您的代码更符合地道的python。可以直接迭代文件。所以代替:
f = inFile.read().splitlines()
您应该使用:
for line in inFile:
现在,我们已经像在python中一样直接在您的文件上运行代码,您只需调用next(inFile)
就可以在文件中获得下一行。这将推进文件迭代器并返回值,并且不会中断您的for
循环。