我正在尝试创建一个小应用程序,它使用pyparsing
从另一个程序生成的文件中提取数据。
这些文件格式如下。
SOME_KEYWORD:
line 1
line 2
line 3
line 4
ANOTHER_KEYWORD:
line a
line b
line c
如何构建有助于提取line 1
,line 2
... line 4
和line a
.. line c
的语法?
我正在尝试制作这样的结构
Grammar = Keyword("SOME_KEYWORD:").supress() + NonEmptyLines + EmptyLine.supress() +\
Keyword("ANOTHER_KEYWORD:").supress() + NonEmptyLines + EmptyLine.supress()
但我不知道如何定义NonEmptyLines
和EmptyLine
。
谢谢。
答案 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']]
在构建语法时,将部分分配给变量并在可能时引用它们确实很有帮助。