我正在使用pyparsing解析表单的表达式:
"and(or(eq(x,1), eq(x,2)), eq(y,3))"
我的测试代码如下所示:
from pyparsing import Word, alphanums, Literal, Forward, Suppress, ZeroOrMore, CaselessLiteral, Group
field = Word(alphanums)
value = Word(alphanums)
eq_ = CaselessLiteral('eq') + Group(Suppress('(') + field + Literal(',').suppress() + value + Suppress(')'))
ne_ = CaselessLiteral('ne') + Group(Suppress('(') + field + Literal(',').suppress() + value + Suppress(')'))
function = ( eq_ | ne_ )
arg = Forward()
and_ = Forward()
or_ = Forward()
arg << (and_ | or_ | function) + Suppress(",") + (and_ | or_ | function) + ZeroOrMore(Suppress(",") + (and_ | function))
and_ << Literal("and") + Suppress("(") + Group(arg) + Suppress(")")
or_ << Literal("or") + Suppress("(") + Group(arg) + Suppress(")")
exp = (and_ | or_ | function)
print(exp.parseString("and(or(eq(x,1), eq(x,2)), eq(y,3))"))
我有以下形式的输出:
['and', ['or', ['eq', ['x', '1'], 'eq', ['x', '2']], 'eq', ['y', '3']]]
列表输出看起来不错。但是对于后续处理,我希望以嵌套字典的形式输出:
{
name: 'and',
args: [
{
name: 'or',
args: [
{
name: 'eq',
args: ['x','1']
},
{
name: 'eq',
args: ['x','2']
}
]
},
{
name: 'eq',
args: ['y','3']
}
]
}
我试过Dict
上课,但没有成功。
是否可以在pyparsing中做到这一点?或者我应该手动格式化列表输出?