Python 表达式计算-递归下降的解析器

Python 表达式计算-递归下降的解析器

  1. #表达式计算-递归下降的解析器
    import re
    import collections

#Token specification
NUM = r’(?P\d+)’
PLUS = r’(?P+)’
MINUS = r’(?P-)’
TIMES = r’(?P*)’
DIVIDE = r’(?P/)’
LPAREN = r’(?P()’
RPAREN = r’(?P))’
WS = r’(?P\s+)’

master_pat = re.compile(’|’.join([NUM,PLUS,MINUS,TIMES,DIVIDE,LPAREN,RPAREN,WS]))

#Tokenizer
Token = collections.namedtuple(‘Token’, [‘type’,‘value’])

def generate_tokens(text):
scanner = master_pat.scanner(text)
for m in iter(scanner.match, None):
tok = Token(m.lastgroup,m.group())
if tok.type != ‘WS’:
yield tok

#Parser
class ExpressionEvaluator:
‘’’
Implementation of a recursive desent parser. Each method implements a single
grammar rule.Use the ._accept() method to test and accept the current lookahead
token.Use the ._expect() method to exactly match and discard the next token
on on the input (or raise a SyntaxError if it doesn’t match).
‘’’

def parse(self,text):
    self.tokens = generate_tokens(text)
    self.tok = None
    self.nexttok = None
    self._advance()
    return self.expr()

def _advance(self):
    'Advance one token ahead'
    self.tok,self.nexttok = self.nexttok, next(self.tokens,None)

def _accept(self,toktype):
    'Test and consume the next token if it matches toktype'
    if self.nexttok and self.nexttok.type == toktype:
        self._advance()
        return True
    else:
        return False

def _expect(self,toktype):
    'Consume next token if it matches toktype or raise SyntaxError'
    if not self._accept(toktype):
        raise SyntaxError('Expected ' + toktype)

#Grammar rules follow
def expr(self):
    "expression ::= term { ('+'|'-') term }*"

    exprval = self.term()
    while self._accept('PLUS') or self._accept('MINUS'):
        op = self.tok.type
        right = self.term()
        if op == 'PLUS':
            #exprval += right
            exprval = ('+', exprval, right)
        elif op == 'MINUS':
            #exprval -= right
            exprval = ('-', exprval,right)
    return  exprval

def term(self):
    "term ::= factor {('*'|'/') factor }*"

    termval = self.factor()
    while self._accept('TIMES') or
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Shinobi_Jack

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值