私はPythonのast(抽象構文木)で遊んでいます。Python astモジュールを使用した構文木のノードを訪問
私は次のように書いて、ASTのすべてのノードを訪問しました。
import ast
class Py2Neko(ast.NodeVisitor):
def generic_visit(self, node):
print type(node).__name__
ast.NodeVisitor.generic_visit(self, node)
def visit_Name(self, node):
print 'Name :', node.id
def visit_Num(self, node):
print 'Num :', node.__dict__['n']
def visit_Str(self, node):
print "Str :", node.s
if __name__ == '__main__':
node = ast.parse("a = 1 + 2")
print ast.dump(node)
v = Py2Neko()
v.visit(node)
はその後Py2Nekoクラスに
def visit_Print(self, node):
print "Print :"
def visit_Assign(self, node):
print "Assign :"
def visit_Expr(self, node):
print "Expr :"
をいくつかのメソッドを追加しました。しかし、それは「印刷」文またはassignementまたは式に遭遇したとき、それが停止し、さらにつもりはないようです。
これは、出力:
Module(body=[Assign(targets=[Name(id='a', ctx=Store())], value=BinOp(left=Num(n=1), op=Add(), right=Num(n=2)))])
Module
Assign :
誰かが私が間違って何をしたか教えてもらえます。私は非終端ノードの場合はPython 2.6.6
大丈夫、あなたが説明したことを得ました、今はっきりしています、ありがとう! – narke