Parsing multiple lines from text file using regex

Jason Friedman jsf80238 at gmail.com
Sun Nov 3 06:12:37 EST 2013


>  Hi,
> I am having an issue with something that would seem to have an easy
> solution, but which escapes me.  I have configuration files that I would
> like to parse.  The data I am having issue with is a multi-line attribute
> that has the following structure:
>
> banner <option> <banner text delimiter>
> Banner text
> Banner text
> Banner text
> ...
> <banner text delimiter>
>
This is an alternative solution someone else posted on this list for a
similar problem I had:

#!/usr/bin/python3
from itertools import groupby
def get_lines_from_file(file_name):
    with open(file_name) as reader:
        for line in reader.readlines():
            yield(line.strip())

counter = 0
def key_func(x):
    if x.strip().startswith("banner") and x.strip().endswith("<banner text
delimiter>"):
        global counter
        counter += 1
    return counter

for key, group in groupby(get_lines_from_file("my_data"), key_func):
    print(list(group)[1:-1])
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20131103/9a189804/attachment.html>


More information about the Python-list mailing list