匹配非空行与pyparsing

时间:2011-04-28 17:34:50

标签: python pyparsing

我正在尝试创建一个小应用程序,它使用pyparsing从另一个程序生成的文件中提取数据。

这些文件格式如下。

SOME_KEYWORD:
line 1
line 2
line 3
line 4

ANOTHER_KEYWORD:
line a
line b
line c

如何构建有助于提取line 1line 2 ... line 4line a .. line c的语法? 我正在尝试制作这样的结构

Grammar = Keyword("SOME_KEYWORD:").supress() + NonEmptyLines + EmptyLine.supress() +\
         Keyword("ANOTHER_KEYWORD:").supress() + NonEmptyLines + EmptyLine.supress()

但我不知道如何定义NonEmptyLinesEmptyLine。 谢谢。

2 个答案:

答案 0 :(得分:7)

我接受它:

    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

结果是:

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

答案 1 :(得分:3)

这会带你到处:

import pyparsing as pp

data = """
SOME_KEYWORD:
line 1
line 2
line 3
line 4

ANOTHER_KEYWORD:
line a
line b
line c
"""

some_kw = pp.Keyword('SOME_KEYWORD:').suppress()
another_kw = pp.Keyword('ANOTHER_KEYWORD:').suppress()
kw = pp.Optional(some_kw ^ another_kw)

# Hint from: http://pyparsing.wikispaces.com/message/view/home/21931601
lines = kw + pp.SkipTo(
    pp.LineEnd() + pp.OneOrMore(pp.LineEnd()) |
    pp.LineEnd() + pp.StringEnd() |
    pp.StringEnd()
)

result = lines.searchString(data.strip())
results_list = result.asList()
# => [['\nline 1\nline 2\nline 3\nline 4'], ['\nline a\nline b\nline c']]

在构建语法时,将部分分配给变量并在可能时引用它们确实很有帮助。