python import ply.lex as lex tokens = ( 'NUMBER', 'PLUS', 'TIMES', ) def t_NUMBER(t): r'\d+' t.value = int(t.value) return t t_PLUS = r'\+' t_TIMES = r'\*' t_ignore = ' \t' def t_error(t): print(f"Unexpected character: {t.value[0]}") t.lexer.skip(1) lexer = lex.lex() python import ply.yacc as yacc def p_expression_plus(p): 'expression : expression PLUS expression' p[0] = p[1] + p[3] def p_expression_times(p): 'expression : expression TIMES expression' p[0] = p[1] * p[3] def p_expression_number(p): 'expression : NUMBER' p[0] = p[1] def p_error(p): print("Syntax error") parser = yacc.yacc() python while True: try: s = input('>>> ') except EOFError: break if not s: continue result = parser.parse(s) print(result)


上一篇:
下一篇:
切换中文