2017-07-24 125 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行和當前行 –