我使用pyparsing来解析下输入:在pyparsing中,如何格式化嵌套的字典输出?
%FSLAX45Y67*%
输出格式我之后,在字典的形式,就是:
{
'notation': 'absolute',
'zeros': 'leading',
'x': {
'integer': 4,
'decimal': 5
},
'y': {
'integer': 6,
'decimal': 7,
},
'gerber-command': 'FS'
}
目前我得到的输出是:
{
'notation': 'absolute',
'decimal': 6,
'zeros': 'leading',
'integer': 6,
'y': ([6, 6], {'integer': [(6, 0)], 'decimal': [(6, 1)]}),
'x': ([6, 6], {'integer': [(6, 0)], 'decimal': [(6, 1)]}),
'gerber-command': 'FS'
}
(请注意,我的问题不是如何使输出看起来正确,而是如何让pyparsing安排我想要的数据。)
用下面的代码:
single_digit = pyp.Regex(r'(\d)').setParseAction(lambda t: int(t[0]))
cmd_format = pyp.Literal('FS')
cmd_format_opt_leading_zeros = pyp.Literal('L').setParseAction(pyp.replaceWith('leading'))
cmd_format_opt_trailing_zeros = pyp.Literal('T').setParseAction(pyp.replaceWith('trailing'))
format_zeros = ((cmd_format_opt_leading_zeros('zeros')) |
(cmd_format_opt_trailing_zeros('zeros')))
format_notation = ((cmd_format_opt_absolute('notation')) |
(cmd_format_opt_incremental('notation')))
format_data = (single_digit)('integer') + single_digit('decimal')
gformat = (inst_del +
cmd_format('gerber-command') +
format_zeros +
format_notation +
'X' + (format_data)('x') +
'Y' + (format_data)('y') +
inst_end +
inst_del)
(一些琐碎的定义中省略)。有什么建议么?
你的第一个建议让我更接近,但仍有一些“残留”:{'y':([4,3],{'integer':[(4,0)],'decimal':[(3,1 )]),'x':([6,5],{'integer':[(6,0)],'decimal':[(5,1)]}),'zeros':'leading' ,'notation':'绝对','gerber-command':'FS'} –
您看到的'残留'只是嵌套的ParseResults的repr输出。尝试使用已定义的名称访问结果:result.notation,result.x.integer,result.y.integer,result.x.decimal等。result.dump()的外观如何? – PaulMcG
result.dump()看起来不错。我想我期望.asDict()输出看起来完全像一本字典,我想不是这种情况,这非常好。 –