【问题标题】:How to match a word, print the line and the next line, over and over in a file如何匹配一个单词,在文件中一遍又一遍地打印该行和下一行
【发布时间】:2019-01-09 02:33:13
【问题描述】:

注册商希望解析包含许多学生数据的文本文件。

输入文件:多个学生数据的文本文件(每个学生文件格式相同)

我已成功找到“模式”并将其打印到文件中,这是我需要的 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')

【问题讨论】:

  • 什么情况下需要“找到匹配后打印下一行”?

标签: python


【解决方案1】:

您应该首先做一些事情来使您的代码更符合 python 的习惯。文件可以直接迭代。所以而不是:

f = inFile.read().splitlines()

你应该只使用:

for line in inFile:

现在我们已经让您的代码直接在您的文件上运行,就像我们在 python 中所做的那样,您只需调用 next(inFile) 即可获取文件中的下一行。这将推进文件迭代器并返回值,并且不会破坏您的 for 循环。

【讨论】:

  • 我进行了更改,代码没有抛出错误,但没有打印第二行。这是代码的样子,我希望写有“4:”的行和后面的行。 if '4:' in line: outfile.write(line + '\n') next (inFile) outfile.write(line + '\n')
  • next(inFile) 推进迭代器并返回新值。您需要将它存储在某个地方(line = next(inFile)),然后编写它会给您带来您期望的价值。
  • 谢谢!我最终这样做了: outfile.write(next(inFile, '').strip() + '\n') 不完全确定条带的作用 - 但它有效。我喜欢 Python!
  • @jbird - 太棒了!如果您获得了所需的帮助,请记住将答案标记为已接受。
猜你喜欢
  • 1970-01-01
  • 2021-05-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-16
  • 2017-02-19
  • 2021-11-04
相关资源
最近更新 更多