使用pyparsing对结构化文本配置文件进行上下文解析

时间:2012-07-24 14:23:29

标签: python parsing pyparsing

我正在尝试使用pyparsing构建一个简单的解析器。

我的示例文件如下所示:

# comment
# comment

name1 = value1
name2 = value2


example_list a
  foo
  bar


grp1 (

example_list2 aa
  foo
  bar


example_list3 bb
  foo
  bar

)



grp2 (

example_list4 x
  foo
  bar

example_list5 x
  foo
  bar

example_list6 x
  foo
  bar
)

到目前为止我提出的解析器看起来像这样:

#!/usr/bin/python
import sys
from pyparsing import *

blank_line = lineStart + restOfLine
comment = Suppress("#") + restOfLine

alias = Word(alphas, alphanums)
name = Word(alphas, alphanums + "_")
value = Word(printables)

parameter = name + Suppress("=") + value
flag = Literal("*") | Literal("#") | Literal("!")
list_item = Optional(flag) + value
list = name + alias + lineEnd + OneOrMore(list_item) + blank_line
group = alias + Suppress("(") + lineEnd + OneOrMore(list) + lineStart + Suppress(")")
script = ZeroOrMore(Suppress(blank_line) | Suppress(comment) | parameter ^ list ^ group)

if __name__ == "__main__":
    print script.parseFile(sys.argv[1])

但当然不起作用。

我认为我需要的是解析器知道如果我们有一个后跟一个等号的字符串,那么我们只需要一个字符串。

如果我们有一个字符串后跟一个括号,那么我们就开始了一个小组。

如果我们有两个字符串,那么我们就开始了一个列表。

我该怎么做?

此外,评论可能也会出现在行尾......

1 个答案:

答案 0 :(得分:0)

我不确定您是否对文件格式有所了解,但您的文件可以很容易地表示为RSON文件(请参阅http://code.google.com/p/rson/)。 RSON格式(和相关的解析器)被开发为JSON的“可读”版本。我在一些项目中使用python RSON解析器。

如果您这样做是为了学习如何解析这样的文件,您仍然可以从RSON解析器中收集一些信息。

相关问题