漂亮的Json来自pyparsing

时间:2017-04-24 21:10:31

标签: python pyparsing

所以,我有一些EBNF形式的表达式来解析一些微分方程组

END = Literal(';').suppress()
POINT = Literal('.')
COMMA = Literal(',').suppress()
COLON = Word(':', max=1).suppress()
EQUAL = Literal('=').suppress()
VARNAME = Word(alphas, max=1)
NATNUM = Word(nums)  # 1234567890
SIGN = oneOf('+ -')
OPER = oneOf('+ - * / ^ ')
REALNUM = Combine(Optional(SIGN) + NATNUM + Optional(POINT + NATNUM))  # Real Numbers 2.3, 4.5
STEP = Dict(Group('Step' + COLON + REALNUM + END))  # Step: 0.01 ;
RANGE = Dict(Group('Range' + COLON + REALNUM + END))  # Range: 2.0 ;
VARINIT = Group(VARNAME + Suppress('=') + REALNUM)  # x=32.31
ZEROVAR = Dict(Group('Vars0' + COLON + VARINIT + Optional(COMMA + VARINIT) + END))
COEFF = Dict(Group('Coeff' + COLON + VARINIT + Optional(COMMA + VARINIT) + END))
EXPESS = Forward()
EXPESS << Combine((REALNUM | VARNAME) + ZeroOrMore(OPER + EXPESS), adjacent=False)
IDENT = Combine('d'+VARNAME)
FUNC = Group(IDENT + EQUAL + EXPESS)
DIFUR = Dict(Group('Exp' + COLON + FUNC + ZeroOrMore(COMMA + FUNC) + END))
STATE = Suppress("Start") + DIFUR + ZEROVAR + COEFF + STEP + RANGE + Suppress("Stop")

我希望通过解析finally STATE表达式来接收这种JSON:

{
'Vars0': {
            'y', '0.55',
            'x', '0.02',
            },
'Exp': {
        'dx': 'a*x-y',
        'dy': 'b*x-y',
        'dz':'800-2*4*x+z'
        },
'Range': '2.0',
'Step': '0.05', 
'Coeff': {
            'a': '5',
            'b': '2'
        }
}

但相反,我有一些丑陋的东西,例如'Vars0':( [(['y','0.55'],{}),(['x','0.02'],{} )], {}) 等等。 我的愚蠢错误是什么? 附:解析纯文本以进行解析可以像this

1 个答案:

答案 0 :(得分:1)

你拥有的不是JSON,它是一个Python字典变量,幸运的是它可以用pprint模块打印出来。

具体来看,请pprint.pprinthttps://docs.python.org/2/library/pprint.html#pprint.pprint

将缩进设置为4且宽度为1可能会产生令您满意的效果。示例:https://ideone.com/pYESaW

相关问题