Home > Software design >  Python how to grep two keywords from a sting in a text file and append into two strings
Python how to grep two keywords from a sting in a text file and append into two strings

Time:10-03

DELIVERED,machine01,2022-01-20T12:57:06,033,Email [Test1] is delivered by [192.168.0.2]

Above is the content from the text file. I have used split(",") method but I have no idea how to make it works as below. Can anyone help with this?

'DELIVERED', 'machine01', '2022-01-20T12:57:06', '033', 'Test1', '192.168.0.2'
with open('log_file.log', 'r') as f:
    for line in f.readlines():
        sep = line.split(",")
        print(sep)

CodePudding user response:

text = "DELIVERED,machine01,2022-01-20T12:57:06,033,Email [Test1] is delivered by [192.168.0.2]"
result = []

for part in text.split(','): # loops the parts of text separated by ","
    result.append(part) # appends this parts into a list

print(result) # prints this list:
['DELIVERED', 'machine01', '2022-01-20T12:57:06', '033', 'Email [Test1] is delivered by [192.168.0.2]']



# or you can do all the same work in just 1 line of code!
result = [part for part in text.split(',')]

print(result)
['DELIVERED', 'machine01', '2022-01-20T12:57:06', '033', 'Email [Test1] is delivered by [192.168.0.2]']

CodePudding user response:

Once you have split using , you then need to use a regular expression to find the contents of the [] in the final string. Since you are doing this over multiple lines, we collect each list in a variable (fields) then print this list of lists at the end:

import re

fields = []
with open('log_file.log', 'r') as f:
    for line in f.readlines():
        sep = line.split(",")
        # Get the last item in the list
        last = sep.pop()
        # Find the values in [] in last
        extras =re.findall(r'\[(.*?)\]', last)
        # Add these values back onto sep
        sep.append(extras[0])
        fields.append(sep)

print(fields)

log_file.log:

DELIVERED,machine01,2022-01-20T12:57:06,033,Email [Test1] is delivered by [192.168.0.2]
DELIVERED,machine02,2022-01-20T12:58:06,034,Email [Test2] is delivered by [192.168.0.3]

Result:

[['DELIVERED', 'machine01', '2022-01-20T12:57:06', '033', 'Test1', '192.168.0.2'], ['DELIVERED', 'machine02', '2022-01-20T12:58:06', '034', 'Test2', '192.168.0.3']]
  • Related