2015-06-17 35 views
0

我是個新手的Python所以原諒任何缺點定義的變量。使用使用Python版本3 - 分割字符串 - 使用等號

我是個Python腳本來觀看已循環日誌的文件夾。 當某一條記錄包含一行字「警報」,我想寫從該行數據到文本文件Output.txt的。 (對駐留在目錄IM看文件)

登錄樣品的樣子:

Normal:Action='Push',Id='1434456544527',Other='BBB' 
Normal:Action='Push',Id='1434456544527',Other='BBB' 
Normal:Action='Push',Id='1434456544527',Other='BBB' 
Normal:Action='Push',Id='1434456544527',Other='BBB' 
Alert:Action='Pull',Id='1434456544527',Other='AAA' 
Normal:Action='Push',Id='1434456544527',Other='BBB' 

所以我想有Output.txt的包含:

Pull,1434456544527,AAA 

這是我的腳本 - 追蹤是從http://code.activestate.com/recipes/577968-log-watcher-tail-f-log/

from trackit import * 
import os 
import re 
import sys 
import subprocess 
text_file = open("Output.txt", "w") 
def callback(filename, lines): 
    for line in lines: 
      if 'Alert' in str(line): 
        #print str(line) 
        text=str(line) 
        cities = text.split("'") 
        matches = re.findall(r"[\w']+", text) 
        print(matches) 
        ####text_file.write('dict = ' + matches + '\n') 
      else: 
        color=1 
watcher = LogWatcher("/folder/logs", callback) 
watcher.loop() 
text_file.close() 

我需要幫助的一塊是如何s當變量定義爲變量='值'

在此先感謝

回答

1

你可以使用正則表達式\w+='([^']*)'


例如,

import re 
line = "Alert:Action='Pull',Id='1434456544527',Other='AAA'" 
matches = re.findall(r"\w+='([^']*)'", line) 
print(matches) 

產生

['Pull', '1434456544527', 'AAA'] 

print(','.join(matches)) 

打印

Pull,1434456544527,AAA 

的正則表達式模式匹配\w+='([^']*)'

\w+   1-or-more alphanumeric character from a-z or A-Z or 0-9 
='    followed by a literal equal sign and single quote 
(    followed by a grouped pattern 
    [   consisting of a character class 
    ^'   which matches any character except a single quote 
    ] 
    *   match the character class 0-or-more times  
) 
'    followed by a literal single quote 
+0

他不想要推他希望所有的事件都帶有Alert。在'Push'事件都沒有警報在該行 – heinst

+0

@heinst:感謝您的指正。這個想法保持不變,因爲OP已經有了用於查找'Alert'行的代碼。 – unutbu

0

test.txt是含有你提供的日誌的示例的文件。我用單引號把它分解喜歡你,和你想的項目是在奇數indicies(1,3,5)

f = open('test.txt', 'r') 
lines = f.readlines() 
f.close() 

for line in lines: 
    if 'Alert' in line: 
     lineSplit = line.split("'") 
     print lineSplit[1] + ',' + lineSplit[3] + ',' + lineSplit[5] 

這產生了:

Pull,1434456544527,AAA 
0
# Read lines from the log file. 
with open('example.log') as f: 
    lines = f.readlines() 

# Filter those lines contains 'Alert:'. 
alerts = [line for line in lines if 'Alert:' in line] 

# Process and then write to the output file. 
with open('output.txt', 'w') as f: 
    for alert in alerts: 
     data = [i for i in alert.split("'")][1::2] 
     f.write(','.join(data))