我很努力用PyParsing分析嵌套結構。我搜索了很多'nested' example uses of PyParsing,但我看不到如何解決我的問題。在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'。所有這些例子都顯示了實現嵌套解析的不同方式,通用性是什麼? http://pyparsing.wikispaces.com/share/view/40834661 – cyrf