pip install ply
python
import ply.lex as lex
tokens = (
'NUMBER',
'PLUS',
'MINUS',
)
t_NUMBER = r'\d+'
t_PLUS = r'\+'
t_MINUS = r'-'
t_ignore = ' \t'
def t_error(t):
print("Illegal character '%s'" % t.value[0])
t.lexer.skip(1)
lexer = lex.lex()
python
import ply.yacc as yacc
def p_expression(p):
'''expression : expression PLUS expression
if len(p) == 4:
if p[2] == '+':
p[0] = p[1] + p[3]
else:
p[0] = p[1] - p[3]
else:
p[0] = p[1]
def p_error(p):
print("Syntax error")
parser = yacc.yacc()
python
while True:
try:
except EOFError:
break
if not s:
continue
result = parser.parse(s)
print(result)
- Ply, https://www.dabeaz.com/ply/ply.html