'How do I print a certain sentence from a file?

I'm trying to print a certain sentence from an external file in python. The file is a .log file.

This is how the file written:

[Mon Dec 05 14:01:48 2005] [notice] workerEnv.init() ok /etc/httpd/conf/workers2.properties
[Mon Dec 05 14:01:48 2005] [error] mod_jk child workerEnv in error state 7

I want to print everything in the first [ ] and everything after [notice] or [error]. I think I need to use the split command but I don't know how.



Solution 1:[1]

Something like this should work:

import re

with open('logfile.log') as logfile:
    for line in map(str.strip, logfile):
        m = re.findall('\[.*?\]', line)
        if len(m) > 1 and m[1] in ('[notice]', '[error]'):
            offset = line.find(m[1]) + len(m[1]) + 1
            print(m[0], line[offset:])

Note:

There are no validity checks here. If a line in the log file doesn't exactly match the format shown in the question, this could fail

Solution 2:[2]

You can do it like this, but probably it won't be the fastest way...

text = ['[Mon Dec 05 14:01:48 2005] [notice] workerEnv.init() ok /etc/httpd/conf/workers2.properties',
        '[Mon Dec 05 14:01:48 2005] [error] mod_jk child workerEnv in error state 7']

for line in text:
    kw = '[notice]' if line.find('[notice]') >= 0 else '[error]' if line.find('[error]') >= 0 else None
    # Filter out every line which does not contain '[notice]' or '[error]'
    if kw:
        tmp = line.split(kw)
        # [1:-2] is needed to get rid of the '[' and ']'
        print(tmp[0][1:-2], tmp[1])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 simre