如果愿意,可以在语法规则里面使用单个的字面字符,例如:
def p_binary_operators(p):
"""expression : expression "+" term
| expression "-" term
term : term "*" factor
| term "/" factor"""
if p[2] == "+":
p[0] = p[1] + p[3]
elif p[2] == "-":
p[0] = p[1] - p[3]
elif p[2] == "*":
p[0] = p[1] * p[3]
elif p[2] == "/":
p[0] = p[1] / p[3]
字符必须像’+’那样使用单引号。除此之外,需要将用到的字符定义单独定义在lex文件的literals
列表里:
# Literals. Should be placed in module given to lex()
literals = ["+","-","*","/" ]
字面的字符只能是单个字符。因此,像’<=’或者’==’都是不合法的,只能使用一般的词法规则(例如t_EQ = r’==’)。