我正在尝试制作一个小型应用程序,它使用 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()
但我不知道如何定义NonEmptyLines
和EmptyLine
。
谢谢。
最佳答案
我的看法:
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/