MiscItems/2010-04-12

php2python第一弹:词法分析

阿暖 <[email protected]>
sender-time     Sent at 18:22 (GMT+08:00). Current time there: 6:54 PM. ✆
reply-to        [email protected]
to      [email protected]
date    Mon, Apr 12, 2010 at 18:22

subject [CPyUG] php2python第一弹:还是自己写个语法分析器吧

语法分析器我第一个想到是antlr 因为GAE用的就是antlr 而且添加到他的第三方库里 ,python之父也对antlr赞不绝口,更重要的是java有一个php2java的项目用的就是antlr.果然很方便就找到一个antlr解析php的语法文件.

大汗,转用PLY(Python Lex Yacc)一个纯python的Lex Yacc. 找了个例子,发现特好用,一目了然,但是语法细节还是要读文档.这就是通用语法分析器不爽的地方.

四则运算的解析器

这就是我写的一个四则运算的解析器(用以前学数据结构做的练习改的)

   1 #coding:utf-8
   2 def parser(s):
   3    #词法分析
   4    token=[ r'\d+',#数值
   5            r'[\(\)\+\-\*\/]',#运算符
   6            ]
   7 
   8    import re
   9    rule="((?:"+")|(?:".join(token)+"))"
  10    rule=re.compile(rule)
  11 
  12    #语法分析
  13    op=['(']#运算符栈
  14    value=[]#数值栈
  15    d={ '+':1,
  16        '-':1,
  17        '*':2,
  18        '/':2,
  19        '(':0,
  20    }#运算符优先级
  21    def _calc():
  22        l=value.pop()
  23        r=eval(value.pop()+op.pop()+l)
  24        value.append(str(r))
  25    def _right_par():
  26        if op[-1]=='(':
  27            op.pop()
  28            return
  29        else:
  30            _calc()
  31            _right_par()
  32    def _parser(m):
  33        i=m.group(1)
  34        if i in '+-*/':
  35            if d[op[-1]]>d[i] :_calc()
  36            op.append(i)
  37        elif i=='(':
  38            op.append(i)
  39        elif i==')':
  40            _right_par()
  41        else:
  42            value.append(i)
  43 
  44    rule.sub(_parser,s)
  45    _right_par()
  46    return value[0]
  47 
  48 while 1:
  49    try:
  50        s = raw_input('calc > ')
  51    except EOFError:
  52        break
  53    print parser(s)


反馈

创建 by -- ZoomQuiet [2010-04-12 10:56:56]

MiscItems/2010-04-12 (last edited 2010-04-12 11:18:38 by flyinflash)