How to grab the lines AFTER a matched line in python

前端 未结 4 1309
[愿得一人]
[愿得一人] 2021-01-05 12:22

I am an amateur using Python on and off for some time now. Sorry if this is a silly question, but I was wondering if anyone knew an easy way to grab a bunch of lines if the

4条回答
  •  失恋的感觉
    2021-01-05 13:06

    You could use a variable to mark where which heading you are currently tracking, and if it is set, grab every line until you find another heading:

    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)
    

    Here's a http://codepad.org snippet that shows how it works: http://codepad.org/KA8zGS9E

    Edit: If you don't care about the actual heading values and just want a list at the end, you can use this:

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

    Basically, you don't really need to track a variable for the heading, instead you can just filter out all lines that match the Heading pattern.

提交回复
热议问题