Matching nonempty lines with pyparsing

前端 未结 2 910
攒了一身酷
攒了一身酷 2021-01-19 07:21

I am trying to make a small application which uses pyparsing to extract data from files produced by another program.

These files have following format.<

2条回答
  •  心在旅途
    2021-01-19 07:45

    My take on it:

        from pyparsing import *
    
        # matches and removes end of line
        EOL = LineEnd().suppress()
    
        # line starts, anything follows until EOL, fails on blank lines,
        line = LineStart() + SkipTo(LineEnd(), failOn=LineStart()+LineEnd()) + EOL
    
        lines = OneOrMore(line)
    
        # Group keyword probably helps grouping these items together, you can remove it
        parser = Keyword("SOME_KEYWORD:") + EOL + Group(lines) + Keyword("ANOTHER_KEYWORD:") + EOL + Group(lines)
        result = parser.parseFile('data.txt')
        print result
    

    Result is:

    ['SOME_KEYWORD:', ['line 1', 'line 2', 'line 3', 'line 4'], 'ANOTHER_KEYWORD:', ['line a', 'line b', 'line c']]
    

提交回复
热议问题