如何在特定行开始阅读文本并停止和特定行
How can I start reading text at a specific line and stop and specific line
长期听众第一次来电,我对此很陌生,所以请多多关照。
我有一个很大的文本文档,我想去掉 header 和页脚。我想触发文本中包含特定字符串的开始和停止阅读行。
filename ='Bigtextdoc.txt'
startlookup = 'Foo'
endlookup = 'Bar'
with open(filename, 'r') as infile:
for startnum, line in enumerate(infile, 1):
if startlookup in line:
data = infile.readlines()
for endnum, line in enumerate(infile, 1):
if endlookup in line:
break
print(data)
像这样我可以读取 header 包含 'Foo' 之后的行,如果我将 data = 行移动到 if endlookup 行之后,它只会读取页脚中从 'Bar'
不知道如何从 Foo 开始到 Bar 停止?
为了便于阅读,我将提取函数中的逻辑,例如:
def lookup_between_tags(lines, starttag, endtag):
should_yield = False
for line in lines:
if starttag in line:
should_yield = True
elif endtag in line:
should_yield = False
if should_yield:
yield line
利用打开的文件是可迭代的这一事实,它可以像这样使用:
with open('Bigtextdoc.txt') as bigtextdoc:
for line in lookup_between_tags(bigtextdoc, 'Foo', 'Bar'):
print(line)
长期听众第一次来电,我对此很陌生,所以请多多关照。
我有一个很大的文本文档,我想去掉 header 和页脚。我想触发文本中包含特定字符串的开始和停止阅读行。
filename ='Bigtextdoc.txt'
startlookup = 'Foo'
endlookup = 'Bar'
with open(filename, 'r') as infile:
for startnum, line in enumerate(infile, 1):
if startlookup in line:
data = infile.readlines()
for endnum, line in enumerate(infile, 1):
if endlookup in line:
break
print(data)
像这样我可以读取 header 包含 'Foo' 之后的行,如果我将 data = 行移动到 if endlookup 行之后,它只会读取页脚中从 'Bar'
不知道如何从 Foo 开始到 Bar 停止?
为了便于阅读,我将提取函数中的逻辑,例如:
def lookup_between_tags(lines, starttag, endtag):
should_yield = False
for line in lines:
if starttag in line:
should_yield = True
elif endtag in line:
should_yield = False
if should_yield:
yield line
利用打开的文件是可迭代的这一事实,它可以像这样使用:
with open('Bigtextdoc.txt') as bigtextdoc:
for line in lookup_between_tags(bigtextdoc, 'Foo', 'Bar'):
print(line)