単純なものを試す。選択
#!/usr/bin/env python import ply.lex as lex tokens = ( 'A', 'B', 'C', 'D', 'E', 'F', ) t_A = r'a' t_B = r'b' t_C = r'c' t_D = r'd' t_E = r'e' t_F = r'f' t_ignore = " \t" def t_error(t): print "Illegal character '%s'" % t.value[0] t.lexer.skip(1) lex.lex() import ply.yacc as yacc def p_input_1(p): 'input : A B C' print "*abc*" def p_input_2(p): 'input : D E F' print "*def*" def p_error(p): print "Syntax error at '%s'" % p.value yacc.yacc() while 1: try: s = raw_input('input > ') except EOFError: break if not s: continue yacc.parse(s)
で、
input > a b c *abc* input > d e f *def*
ちょっと違う書きかた。
#!/usr/bin/env python import ply.lex as lex tokens = ( 'A', 'B', 'C', 'D', 'E', 'F', ) t_A = r'a' t_B = r'b' t_C = r'c' t_D = r'd' t_E = r'e' t_F = r'f' t_ignore = " \t" def t_error(t): print "Illegal character '%s'" % t.value[0] t.lexer.skip(1) lex.lex() import ply.yacc as yacc def p_input(p): '''input : A B C | D E F''' if p[1] == 'a': print "*abc*" else: print "*def*" def p_error(p): print "Syntax error at '%s'" % p.value yacc.yacc() while 1: try: s = raw_input('input > ') except EOFError: break if not s: continue yacc.parse(s)
で、
input > a b c *abc* input > d e f *def*
分岐の正しい仕方は、まだ不明