python - 使用 pyparsing 匹配非空行

标签 python pyparsing

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

这些文件具有以下格式。

SOME_KEYWORD:
line 1
line 2
line 3
line 4

ANOTHER_KEYWORD:
line a
line b
line c

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

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

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

最佳答案

我的看法:

    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']]

关于python - 使用 pyparsing 匹配非空行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5822709/

相关文章:

python - pyparsing 以最一般的形式解析 python 函数调用

python - Pyparsing - token 的顺序不可预测

python - 更改 is_superuser Django 的 verbose_name

Python 2.7 - Outlook Win32com.client 无法从 .msg 获取发件人的实际电子邮件地址

python - 在 Jinja2 模板中隐藏不可访问的链接

python - 解析示例

python - 如何在Python中以表格形式查看系列

用于字节数日期的 Python 正则表达式

python - 对 unicode 字母进行 Pyparsing

python - PyParsing Optional() 挂起