2011-07-20 21 views
-3

我有一個30000行文本文件,需要使用Python進行修改。我想要做的是以下幾點:Python在條件爲大文本文件的隨機位置插入一行

  1. 有具有關鍵字1以下某個設備名稱的文件中的特定關鍵字1。我需要在所有行識別關鍵字1和檢索所有設備的名稱,然後將它們存儲在一個列表供以後使用

    我已使用正則表達式

  2. 有一次我的設備名稱列表來實現這一點,我需要在文件的一系列特定位置插入帶有「固定格式+設備名稱」的換行符以下關鍵字2

    這是我遇到問題的地方。

    最初我使用了簡單的計數方法。我在整個文件中找到了pattern.search(line),一旦識別出keyword1,就通過計算i + 5來定位插入位置,其中i是識別關鍵字1的行的索引。但是,事實證明文件中的行順序很重要,所以我只需要在關鍵字2所在的行之後插入新行。更麻煩的是關鍵字2存在於文件的任何地方。只有那些需要考慮關鍵字1之後7行內的關鍵字2。

舉個例子:

This is a random line with KEYWORD2  <--- this keyword2 is not considered 
This is a random line 
This is a random line 
This is a random line, KEYBOARD1 "DEVICE NAME"  <--- id keyword1 and record DEVICE 
This is a random line 
This is a random line 
This is a random line 
This is a random line 
This is a random line with KEYWORD2  <--- this keyword2 is considered 

任何建議表示讚賞。在此先感謝

+0

他們是什麼樣的設備? – tomasz

+0

迄今爲止編寫的代碼通常對您的問題回答良好有幫助。如果可以的話,請提供它 - 您可能只需要做一些小改動! –

+0

它們只是電路元件的設備名稱 – Steven

回答

1

我......想你應該有這樣的事情來解決:

with open('input.txt') as fhi, open('output.txt', 'w') as fho: 
    for line in fhi: 
    if not pattern.search(line): 
     # if there is no match write the line to the output file and proceed. 
     fho.write(line) 
     continue 

    # if we get this far we found a match. Scan up to seven lines. 
    for i in range(7): 
     toCheck = next(fhi) 

     if not pattern2.search(toCheck): 
     # if we don't find the 2nd keyword write the line, continue the sub-loop. 
     fho.write(toCheck) 
     continue 

     # if we get this far we found the second pattern. Add our newline. 
     fho.write(toCheck) 
     fho.write('\r\n') 

這是使用多文件語法與在2.7推出。在早期版本中,您必須嵌套with語句或手動管理您的文件句柄。

+0

感謝g.d.d.c!這幾乎解決了我的問題。我原來的問題應該已經說清楚了。 DEVICE需要根據檢索的位置插入換行符。例如:這是一行\ n這是一行,KEYWORD1,DEVICE1 \ n這是一行\ n這是一行,KEYWORD2 \ n這是一個換行符,DEVICE1這個模式將需要保存在整個文件中。你會怎麼做呢?此時,我已經準備好DEVICE列表。提前致謝 – Steven

0

您可以爲此使用一個正則表達式。舉例:

In [13]: p = re.compile('(.*kw1.*\n.*\n.*kw2.*$)', re.MULTILINE) 

In [14]: p.sub(r'\1\n', 'bla kw1\nbla \n bla kw2 blub') 
Out[14]: 'bla kw1\nbla \n bla kw2 blub\n' 

您必須將此表達式擴展爲7行並添加相關關鍵字。