如何使用文档示例获得构造树?

How can I get a constructed tree in ply using the documentation example?

documentation 他们展示了这个构建树的例子:

 def p_expression_binop(p):
     '''expression : expression PLUS expression
                   | expression MINUS expression
                   | expression TIMES expression
                   | expression DIVIDE expression'''

     p[0] = ('binary-expression',p[2],p[1],p[3])

 def p_expression_group(p):
     'expression : LPAREN expression RPAREN'
     p[0] = ('group-expression',p[2])

 def p_expression_number(p):
     'expression : NUMBER'
     p[0] = ('number-expression',p[1])

但我的问题是,一旦创建了树,这些节点会去哪里?或者如何从 p[0]?

访问它们

只要确保节点一直传递到顶部(即开始符号的动作),您只需使用调用[的return值即可=10=].

来自文档:

Whenever the starting rule is reduced by the parser and no more input is available, parsing stops and the final value is returned (this value will be whatever the top-most rule placed in p[0]).