使用Python Version 3 - Split String - 使用Equals符号定义的变量

时间:2015-06-17 12:46:47

标签: python python-3.x split

我是一个Python新手,所以原谅任何缺点。

我使用Python脚本来观看已循环日志的文件夹。 当其中一个日志包含单词“Alert:”时,我想将该行的数据写入文本文件Output.txt。

日志示例(驻留在正在观看的目录中的文件)如下所示:

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

这是我的脚本 - trackit来自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()

我需要帮助的部分是当变量定义为 variable ='Value'时如何分割线?

提前致谢

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

test.txt是包含您提供的日志示例的文件。我把它和你一样的单引号分开,你想要的项目是奇怪的标记(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

答案 2 :(得分: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))