[英]Using Python Version 3 - Split String - Variables defined using Equals sign
我是Python新手,因此可以原谅任何缺点。
我正在使用Python脚本来监视循环了日志的文件夹。 当其中一个日志包含一行“ Alert:”字样时,我想将该行中的数据写入文本文件Output.txt。
日志样本(位于驻留在im watch目录中的文件)看起来像:
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'时拆分行?
提前致谢
您可以使用regex模式\\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
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
# 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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.