How to grab strings AFTER matched string in python

I am an amateur using Python for some time. Sorry if this is a stupid question, but I was wondering if anyone knows an easy way to grab a bunch of lines if the input file format looks like this:

"Heading 1

Line 1

Line 2

Line 3

Heading 2

Line 1

Line 2

Line 3 "

I won’t know how many lines after each heading, but I want to grab them all. All I know is the name or regular expression pattern for the header.

The only way I know to read the file is the path "for the line in the file:", but I don’t know how to capture the lines AFTER which line I’m leading to now. Hope this makes sense and thanks for the help!

* ! , , , , . ... ? *

+5
4

def group_by_heading( some_source ):
    buffer= []
    for line in some_source:
        if line.startswith( "Heading" ):
            if buffer: yield buffer
            buffer= [ line ]
        else:
            buffer.append( line )
    yield buffer

with open( "some_file", "r" ) as source:
    for heading_and_lines in group_by_heading( source ):
        heading= heading_and_lines[0]
        lines= heading_and_lines[1:]
        # process away.
+7

, , , , :

data = {}
for line in file:
    line = line.strip()
    if not line: continue

    if line.startswith('Heading '):
        if line not in data: data[line] = []
        heading = line
        continue

    data[heading].append(line)

http://codepad.org, , : http://codepad.org/KA8zGS9E

. , :

data = []
for line in file:
    line = line.strip()
    if not line: continue

    if line.startswith('Heading '):
        continue

    data.append(line)

, , , .

+4

, , dict, "Heading", - .

odd_map = {}
odd_list = []
with open(file, 'r') as myFile:
    lines = myFile.readlines()
    for line in lines:
        if "Heading" in line:
            odd_list = []
            odd_map[line.strip()] = odd_list
        else:    
            odd_list.append(line.strip())

for company, odds in odd_map.items():
    print(company)
    for odd in odds:
        print(odd)
+1

Python, .

int header_found = 0;

[, , ]

(header_found == 1)   [ ];   header_found = 0;

if (line = ~/[regexp ]/)   header_found = 1;

, , , , , - .

0

All Articles