def t_NUMBER(t):
r'\d+'
t.value = int(t.value)
return t
def p_expression_plus(p):
'expression : expression PLUS expression'
p[0] = p[1] + p[3]
python
from ply.lex import lex
from ply.yacc import yacc
tokens = (
'NUMBER',
'PLUS',
)
t_PLUS = r'\+'
t_ignore = ' \t'
def t_NUMBER(t):
r'\d+'
t.value = int(t.value)
return t
def t_error(t):
t.lexer.skip(1)
def p_expression_plus(p):
'expression : expression PLUS expression'
p[0] = p[1] + p[3]
def p_expression_number(p):
'expression : NUMBER'
p[0] = p[1]
def p_error(p):
if p:
else:
lexer = lex()
parser = yacc()
data = '1 + 2 + 3'
lexer.input(data)
result = parser.parse(lexer=lexer)