2016-02-24 104 views
0

我想爲我的txt文件中的每個換行應用正則表達式。 例如Python腳本解析優化

comments={ts=2010-02-09T04:05:20.777+0000,comment_id=529590|2886|LOL|Baoping Wu|529360} 
comments={ts=2010-02-09T04:20:53.281+0000, comment_id=529589|2886|cool|Baoping Wu|529360} 
comments={ts=2010-02-09T05:19:19.802+0000,comment_id=529591|2886|ok|Baoping Wu|529360} 

我的Python代碼是:

import re 
p = re.compile(ur'(comment_id=)(\d+)\|(\d+)\|([^|]+)\|([^|]+)\|(\d+)', re.MULTILINE|re.DOTALL) 
#open = 
test_str = r"comments={ts=2010-02-09T04:05:20.777+0000, comment_id=529590|2886|LOL|Baoping Wu|529360}" 
subst = ur"\1\2, user_id = \3, comment='\4', user= '\5', post_commented=\6" 

result = re.sub(p, subst, test_str) 
print result 

我想MULTILINE的幫助來解決它,但它不工作。 誰能幫我

的第一行輸出應該

comments={ts=2010-02-09T04:05:20.777+0000, comment_id=529590, user_id = 2886, comment='LOL', user= 'Baoping Wu', post_commented=529360} 

我的問題是隻應用正則表達式的每一行,並把它寫在txt文件。

+1

什麼不行?什麼是你得到的錯誤或輸出與你真正想要的? –

+1

它不是全球性的嗎?我沒有看到多行或dotall的需要。 – sln

+0

@sln我在txt文件中有成千上萬行。這就是爲什麼它對我很重要 –

回答

1

您的正則表達式不需要使用MULTILINE或DOTALL。您可以立即替換整個文檔。 In action

import re 

with open('file.txt', 'r') as f: 
    txt = f.read() 

pattern = r'(comment_id=)(\d+)\|(\d+)\|([^|]+)\|([^|]+)\|(\d+)' 
repl = r"\1\2, user_id = \3, comment='\4', user= '\5', post_commented=\6" 

result = re.sub(pattern, repl, txt) 
with open('file2.txt', 'w') as f: 
    f.write(result) 
+0

我試過了,但它不適用replacemts。它是相同的文件 –

+0

嗯,爲我工作。你有沒有注意到它正在寫出一個單獨的文件? –

+0

啊,好的...一瞬間。我應該創建一個名爲file2.txt的文件嗎? –