gpt4 book ai didi

python - 如何仅在特定字符串之后读取文本文件中的行?

转载 作者:太空狗 更新时间:2023-10-29 17:52:06 25 4
gpt4 key购买 nike

我想将文本文件中特定字符串之后的所有行读入字典。我想对数千个文本文件执行此操作。

我能够使用以下代码(来自 this answer )识别并打印出特定字符串('Abstract'):

for files in filepath:
with open(files, 'r') as f:
for line in f:
if 'Abstract' in line:
print line;

但是我如何告诉 Python 开始读取仅在字符串之后的行?

最佳答案

当你到达你想开始的行时,开始另一个循环:

for files in filepath:
with open(files, 'r') as f:
for line in f:
if 'Abstract' in line:
for line in f: # now you are at the lines you want
# do work

文件对象是它自己的迭代器,所以当我们到达其中包含 'Abstract' 的行时,我们从该行继续迭代,直到我们使用了迭代器。

一个简单的例子:

gen = (n for n in xrange(8))

for x in gen:
if x == 3:
print('Starting second loop')
for x in gen:
print('In second loop', x)
else:
print('In first loop', x)

产生:

In first loop 0
In first loop 1
In first loop 2
Starting second loop
In second loop 4
In second loop 5
In second loop 6
In second loop 7

您还可以使用 itertools.dropwhile消耗线到你想要的点:

from itertools import dropwhile

for files in filepath:
with open(files, 'r') as f:
dropped = dropwhile(lambda _line: 'Abstract' not in _line, f)
next(dropped, '')
for line in dropped:
print(line)

关于python - 如何仅在特定字符串之后读取文本文件中的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27805919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com