2015-10-06 66 views
0

我是新來的python和這個網站,所以先謝謝你,你的理解。這是我第一次嘗試Python腳本。python正則表達式來自大文本文件的特定塊文本

我有我認爲是一個性能問題,試圖解決這個問題,這導致我沒有得到任何數據。

此代碼適用於幾頁文本文件,但是當我嘗試在我的35MB真實數據文本文件上使用它時,它只是點擊CPU並且沒有返回任何數據(現在> 24小時)。

下面是從35MB文本文件中的實際數據的一個片段:

D)dddld 
d00d90d 
dd 

ddd 

vsddfgsdfgsf 

dfsdfdsf 
aAAAAAa 

221546 
29806916295 
Meowing 
fs:/mod/umbapp/umb/sentbox/221546.pdu 
2013:10:4:22:11:31:4 

sadfsdfsdf 
sdfff 
ff 
f 

29806916295 
What's your cat doing? 
fs:/mod/umbapp/umb/sentbox/10955.pdu 
2013:10:4:22:10:15:4 

aaa 
aaa 
aaaaa 

我試圖複製到一個新的文件:

29806916295 
Meowing 
fs:/mod/umbapp/umb/sentbox/221546.pdu 
2013:10:4:22:11:31:4 

29806916295 
What's your cat doing? 
fs:/mod/umbapp/umb/sentbox/10955.pdu 
2013:10:4:22:10:15:4 

我的Python代碼是:

import re 

with open('testdata.txt') as myfile: 
    content = myfile.read() 

text = re.search(r'\d{11}.*\n.*\n.*(\d{4})\D+(\d{2})\D+(\d{1})\D+(\d{2})\D+(\d{2})\D+\d{2}\D+\d{1}', content, re.DOTALL).group() 
with open("result.txt", "w") as myfile2: 
    myfile2.write(text) 

回答

0

正則表達式不是搜索字符串的最快方法。你還通過一個非常大的字符串(35MB)來解決問題。通常不推薦將整個文件讀入內存,因爲您可能會遇到內存問題。

從您的正則表達式模式來看,您似乎希望捕獲以11位字符串開頭並以某個時間行字符串結尾的4行組。試試這個代碼:

import re 

start_pattern = re.compile(r'^\d{11}$') 
end_pattern = re.compile(r'^\d{4}\D+\d{2}\D+\d{1}\D+\d{2}\D+\d{2}\D+\d{2}\D+\d{1}$') 

capturing = 0 
capture = '' 

with open('output.txt', 'w') as output_file: 
    with open('input.txt', 'r') as input_file: 
     for line in input_file: 
      if capturing > 0 and capturing <= 4: 
       capturing += 1 
       capture += line     
      elif start_pattern.match(line): 
       capturing = 1 
       capture = line 

      if capturing == 4: 
       if end_pattern.match(line): 
        output_file.write(capture + '\n') 
       else: 
        capturing = 0 

它逐行地遍歷輸入文件。如果找到與start_pattern匹配的行,則會再讀入3行。如果第4行與end_pattern匹配,它會將整個組寫入輸出文件。

+0

這就像一個魅力,非常感謝你的答案! – Rob

相關問題