gpt4 book ai didi

Python读取两个字符串之间的特定文本行

转载 作者:太空狗 更新时间:2023-10-30 02:13:02 24 4
gpt4 key购买 nike

我无法让 python 读取特定行。我正在做的是这样的:

lines of data not needed
lines of data not needed
lines of data not needed

--------------------------------------
***** REPORT 1 *****
--------------------------------------

[key] lines of interest are here
[key] lines of interest are here
[key] lines of interest are here
[key] lines of interest are here
[key] lines of interest are here #This can also be the EOF

--------------------------------------
***** REPORT 2 *****
--------------------------------------

lines of data not needed
lines of data not needed
lines of data not needed #Or this will be the EOF

我尝试过的是这样的:

flist = open("filename.txt").readlines()

for line in flist:
if line.startswith("\t**** Report 1"):
break
for line in flist:
if line.startswith("\t**** Report 2"):
break
if line.startswith("[key]"):
#do stuff with data

但是,当文件结束时没有结束定界符时我遇到了问题...例如报告 #2 未显示时。什么是更好的方法?

最佳答案

稍微修改一下,看起来应该可以解决您的问题:

flist = open("filename.txt").readlines()

parsing = False
for line in flist:
if line.startswith("\t**** Report 1"):
parsing = True
elif line.startswith("\t**** Report 2"):
parsing = False
if parsing:
#Do stuff with data

如果您想避免解析行“* Report 1”...本身,只需将开始条件放在if parsing 之后,即

flist = open("filename.txt").readlines()

parsing = False
for line in flist:

if line.startswith("\t**** Report 2"):
parsing = False
if parsing:
#Do stuff with data
if line.startswith("\t**** Report 1"):
parsing = True

关于Python读取两个字符串之间的特定文本行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11732383/

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