Pythonソースの構文解析…parse

Pythonソースの構文解析を行うモジュールparseを使ってみた。

下記は解析後のツリー構造を表示するプログラム
import parser
import symbol
import token
from types import *

def level( node, indent ):
 
 id = node[0]
 for child in node[1:]:
  
  # 終端
  if type(child) is StringType:
   name = token.tok_name.get(id)
   print ('-'*indent) + "(%s '%s')" % (name,child)
  
  # ノード
  elif type(child) is ListType:
   
   name = symbol.sym_name.get(id)
   print ('-'*indent) + ("<%s(%d)> " % (name,id)) +str(len(child))
   level( child, indent+1 )
  
  else:
   print type(child)


def main():
 
 fp = open( "test.txt", 'r' )
 text = fp.read()
 
 try:
  ast = parser.suite( text )
  
 except SyntaxError,e:
  print "error!:"+str(e)
  raise
 else:
  level( ast.tolist(), 0 )

if __name__ == '__main__':
    main()

例えば、下記のソースを放り込むと
a+5
こうなります。
 2
- 3
-- 2
--- 2
---- 2
----- 2
------ 2
------- 2
-------- 2
--------- 2
---------- 2
----------- 2
------------ 2
------------- 2
-------------- 4
--------------- 2
---------------- 2
----------------- 2
------------------ 2
------------------- 2
--------------------(NAME 'a')
--------------- 2
----------------(PLUS '+')
--------------- 2
---------------- 2
----------------- 2
------------------ 2
------------------- 2
--------------------(NUMBER '5')
-- 2
---(NEWLINE '')
 2
-(NEWLINE '')
 2
-(ENDMARKER '')

コメント

このブログの人気の投稿

nginxでlocalhostとしてアクセスをサーバーに転送する方法

Android・・・テキスト描画あれこれ, ascent(), descent()等

Android:stateに応じて切り替わるdrawable・・・StateListDrawable