Python 读取两个字符串之间的特定文本行 [英] Python read specific lines of text between two strings

查看:16
本文介绍了Python 读取两个字符串之间的特定文本行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在让 python 读取特定行时遇到问题.我正在做的事情是这样的:

I am having trouble getting python to read specific lines. What i'm working on is something like this:

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

我尝试过的事情是这样的:

What I've attempted was something such as:

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 时.什么是更好的方法?

However, I have a problem when the file ends without a end delimiter... Such as when report #2 is not displayed. What is a better approach?

推荐答案

一个看起来应该可以解决您的问题的轻微修改:

One slight modification which looks like it should cover your problem:

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之后,即

If you want to avoid parsing the line "* Report 1"... itself, simply put the start condition after the if parsing, i.e.

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 读取两个字符串之间的特定文本行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆