How to grab the lines AFTER a matched line in python

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

提交回复
热议问题