【发布时间】:2014-08-08 03:04:58
【问题描述】:
我正在努力使用 PyParsing 解析嵌套结构。我搜索了很多'nested' example uses of PyParsing,但我不知道如何解决我的问题。
这是我的内部结构:
texture_unit optionalName
{
texture required_val
prop_name1 prop_val1
prop_name2 prop_val1
}
这是我的外部结构的样子,但它可以包含零个或多个内部结构。
pass optionalName
{
prop_name1 prop_val1
prop_name2 prop_val1
texture_unit optionalName
{
// edit 2: showing use of '.' character in value
texture required_val.file.name optional_val // edit 1: forgot this line in initial post.
// edit 2: showing potentially multiple values
prop_name3 prop_val1 prop_val2
prop_name4 prop_val1
}
}
我成功解析了内部结构。这是我的代码。
prop_ = pp.Group(pp.Word(pp.alphanums+'_')+pp.Group(pp.OneOrMore(pp.Word(pp.alphanums+'_'+'.'))))
texture_props_ = pp.Group(pp.Literal('texture') + pp.Word(pp.alphanums+'_'+'.')) + pp.ZeroOrMore(prop_)
texture_ = pp.Forward()
texture_ << pp.Literal('texture_unit').suppress() + pp.Optional(pp.Word(pp.alphanums+'_')).suppress() + pp.Literal('{').suppress() + texture_props_ + pp.Literal('}').suppress()
这是我解析外部结构的尝试,
pass_props_ = pp.ZeroOrMore(prop_)
pass_ = pp.Forward()
pass_ << pp.Literal('pass').suppress() + pp.Optional(pp.Word(pp.alphanums+'_'+'.')).suppress() + pp.Literal('{').suppress() + pass_props_ + pp.ZeroOrMore(texture_) + pp.Literal('}').suppress()
当我说: pass_.parseString(testPassStr)
我在控制台中看到应为“}”的错误。
我认为这与C struct example 非常相似,但我不确定缺少的魔法是什么。我也很好奇使用nestedExpr时如何控制生成的数据结构。
【问题讨论】:
-
这是另一个支持嵌套结构的示例。看起来它使用了“pyparsing.Dict”。所有这些例子都展示了实现嵌套解析的不同方式,有什么共同点? pyparsing.wikispaces.com/share/view/40834661