2017-07-24 124 views
0

我想弄清楚如何在匹配的单词前后提取3行。Python,在匹配前后提取3行

目前,我的词被发现。我写了一些文本来测试我的代码。而且,我想出了如何在比赛结束后打印三条线。

但是,我很难弄清楚如何在单词“secure”之前打印三行。

这是我到目前为止有:

from itertools import islice 
with open("testdoc.txt", "r") as f: 
for line in f: 
    if "secure" in line: 
     print("".join(line)) 
     print ("".join(islice(f,3))) 

这里是我的测试中创建的文本:您需要缓冲你的线条,所以你可以记得他们

---------------------------- 
This is a test to see 
if i can extract information 
using this code 
I hope, I try, 
maybe secure shell will save thee 
Im adding extra lines to see my output 
hoping that it comes out correctly 
boy im tired, sleep is nice 
until then, time will suffice 
+0

你尝试过什么到目前为止不工作的第一个?我发现没有试图保留以前读取的行,以防在发现关键字时需要它们。 – Aaron

回答

0

。最简单的方法是把所有的线只是加载到一个列表:

with open("testdoc.txt", "r") as f: 
    lines = f.readlines() # read all lines into a list 
    for index, line in enumerate(lines): # enumerate the list and loop through it 
     if "secure" in line: # check if the current line has your substring 
      print(line.rstrip()) # print the current line (stripped off whitespace) 
      print("".join(lines[max(0,index-3):index])) # print three lines preceeding it 

但是如果你需要存储效率达到最高,你可以使用缓冲区进行的最后3行存储为您遍历通过行的文件行。 A collections.deque对此非常理想。

1

我想出了这个解决方案,只需添加在列表中的上线,以及删除后4个元素

from itertools import islice 

with open("testdoc.txt", "r") as f: 
    linesBefore = list() 
    for line in f: 
     linesBefore.append(line.rstrip()) 
     if len(linesBefore) > 4: #Adding up to 4 lines 
      linesBefore.pop(0) 
     if "secure" in line: 
      if len(linesBefore) == 4: # if there are at least 3 lines before the match 
       for i in range(3): 
        print(linesBefore[i]) 
      else: #if there are less than 3 lines before the match 
       print(''.join(linesBefore)) 
      print("".join(line.rstrip())) 
      print ("".join(islice(f,3))) 
+0

谢谢!我假设linesBefore.pop将选定的行移动到顶部? – jrooz

+0

'linesBefore'存储3行之前和当前行,一旦它添加另一行''linesBefore.pop(0)'删除列表中的第一个元素,再次留下3行和当前行 –