我的输入正在从简单的2级嵌套列表发展到复杂的嵌套列表列表。我看到pyparsing.nestedExpr()是蜜蜂在这种情况下的膝盖,但我仍然希望建立一个嵌套的Dict结构。
随着基础知识逐渐消失,我已经精心设计了这个:
import pyparsing as pp
innput_works = '''
(unitsOfMeasure
(altitudeUnits "m")
(capacitanceUnits "pF")
(designUnits "MIL")
(drawingUnits "MIL")
(drawingAccuracy 2)
(drawingHeight 28000)
)''
# recursive dict
innput_doesnt_work = '''
(parameterFile "out.tf"
(revision "15.6")
(xcoord 1234.567)
(ycoord -3456.890)
(unitsOfMeasure
(altitudeUnits "m")
(capacitanceUnits "pF")
(designUnits "MIL")
(drawingUnits "MIL")
(drawingAccuracy 2)
(drawingHeight 28000)
)
)'''
v_string = pp.Word(pp.alphanums+'_'+'-'+'.')
v_quoted_string = pp.Combine( '"' + v_string + '"')
v_number = pp.Regex(r'[+-]?(?P<float1>\d+)(?P<float2>\.\d+)?(?P<float3>[Ee][+-]?\d+)?')
keyy = v_string
valu = pp.Or( [ v_string, v_quoted_string, v_number])
item = pp.Group( pp.Literal('(').suppress() + keyy + pp.OneOrMore( valu) + pp.Literal(')').suppress() )
# some magic - use Forward to make the diccts self-referential and thus recursive
diccts = pp.Forward()
diccts << pp.Group( pp.Literal('(').suppress() + \
keyy + \
pp.Optional( valu) + \
pp.OneOrMore( pp.Or( item, diccts)) + \
pp.Literal(')').suppress() )
print "diccts_innput_works yields: ", diccts.parseString( innput_works)
print "diccts_innput_doesnt_work yields: ", diccts.parseString( innput_doesnt_work
innput_doesnt_work像6,col 5一样窒息,好像是自我引用的 pp.OneOrMore(pp.Or(item,diccts)) 没有被人看见。
TIA,
code_warrior
答案 0 :(得分:0)
发布后3秒发现我的错误:
pp.OneOrMore( pp.Or( item, diccts )) + \ # wrong
pp.OneOrMore( pp.Or( [item, diccts] )) + \ # right
没关系,没有什么可看的,继续前进。
THX,
code_warrior