在列表中找到行后,Python停止迭代

时间:2018-12-26 05:22:18

标签: python-3.x

我正在尝试搜索“从这里”和“!”之间的所有行。但是一旦找到代码,代码也将继续运行!。

我要处理的行如下:

文件从此处开始

几行

从这里

这里还有其他几行

几行

这里也有东西

下面的代码给我输出为:

开始

这里还有其他几行

几行

!这里也有东西

代码:

def recursion(start,end):

log = False
buffer=""
for line in lines:
    if re.search(start,lines):
        buffer = line
        log = True
    elif re.search(end,lines):

        buffer += lines
        log = False
    elif log:
        buffer += lines


return buffer

file1=open('test.txt','w')
op1=recursion('from here','!')

file1.writelines(op1)

问候 马赫什

1 个答案:

答案 0 :(得分:0)

找到结束字符串后,需要在else子句中添加一个break。另外,应该在缓冲区后面附加“行”而不是“行”。

这是固定版本:

def recursion(start, end):
  log = False
  buffer=""

  for line in lines.split('\n'):
    if start in line:
      buffer = line + '\n'
      log = True
    elif end in line:
      buffer += line
      log = False
      break
    elif log:
      buffer += line + '\n'
  return buffer

在迭代方法中,简单的字符串搜索功能应该会有所帮助。不需要。

这是基于一线式re的实现:

def recursion(start,end):
    return re.findall('(from here.*?!)', lines, re.DOTALL)[0]

输出

$ cat test.txt
cat: test.txt: No such file or directory
$ 

$ cat bar.py
import re
lines = """
file started here
few lines
from here
some other lines here
few more lines
!
!
!
something here as well
!
Code below give me output as:
start
some other lines here
few more lines
!
!
!something here as well
!
"""

def recursion(start,end):
  return re.findall('(from here.*?!)', lines, re.DOTALL)[0]

file1=open('test.txt','w')
op1=recursion('from here','!')
file1.writelines(op1)
$ 

$ python bar.py
$ 

$ cat test.txt
from here
some other lines here
few more lines
!$