How to grab the lines AFTER a matched line in python

前端 未结 4 1292
[愿得一人]
[愿得一人] 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.

    0 讨论(0)
  • 2021-01-05 13:22

    Generator Functions

    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.
    
    0 讨论(0)
  • 2021-01-05 13:25

    Other than a generator, I think we can create a dict where the key is "Heading" and the value is one list to save the lines. Here is the code

    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)
    
    0 讨论(0)
  • 2021-01-05 13:26

    I don't really know Python, but here's a bit of pseudocode.

    int header_found=0;

    [start where loop where you're looping through lines of file]

    if(header_found==1) [grab line]; header_found=0;

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

    The idea is to have a variable that keeps track of whether or not you've found a header, and if you have, to grab the next line.

    0 讨论(0)
提交回复
热议问题