2016-04-07 45 views
0

我有一个文本文件。一旦模式匹配发生,我想打印行,直到找到下一个模式。文本处理:如果条件和循环内另一个循环

for line in text: 
    if pattern in line: 
     if another_pattern in line: 
      print all the lines until pattern_X is found. 
      Continue with the execution from the next line 

这应该对整个文本完成,即模式'pattern'和'another_pattern'将会匹配多次。

回答

2

您可以使用变量来跟踪您是否在要打印的部分。

在伪代码,它可能看起来像:

needToPrint = False 
for line in text: 
    if needToPrint: 
    print line 
    if pattern in line: 
    needToPrint = True 
    if another_pattern in line: 
    needToPrint = False 

(但尤其要注意限制条件,如果你要使用这个片段)

+0

我需要打印的行这两个模式匹配太... –

+0

所以它应该工作,因为只要我们没有看到结束模式,那么'needToPrint'将是真实的,因此我们将打印行 – gturri