简体   繁体   中英

Using Python Version 3 - Split String - Variables defined using Equals sign

Im a Python newbie so forgive any shortcomings.

Im using a Python script to watch a folder that has cycled logs. When one of the logs contains a line the word "Alert:" , I want to write data from that line out to text file Output.txt.

Log Sample ( of files that reside in the directory im watching ) looks like:

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'

So I would like to have Output.txt contain:

Pull,1434456544527,AAA

This is my script - the trackit is from 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()

The piece I need assistance with is how to split out the line when variables are defined as variable='Value' ?

Thanks in advance

You could use regex pattern \\w+='([^']*)' .


For example,

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

yields

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

and

print(','.join(matches))

prints

Pull,1434456544527,AAA

The regex pattern \\w+='([^']*)' matches

\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 is a file containing the log sample you provided. I split it by the single quote like you, and the items you want are at the odd 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]

This yields:

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM