我需要使用ply從正則表達式創建AST。例如,如果RE是(a | b *)abc,我想將一個縮減的元組作爲(':',(':',(':',('|','a',(' *','b')),'a'),'b'),'c')< - ':'表示只是將字符串分成兩部分。如何在python中設置ply的yacc的優先級?
這是我的代碼。
tokens = (
"SYMBOL",
"LBRACKET",
"RBRACKET",
"STAR",
"UNION"
)
t_ignore = ' \t\n'
t_SYMBOL = r'[a-zA-Z0-9]'
t_LBRACKET = r'\('
t_RBRACKET = r'\)'
t_STAR = r'\*'
t_UNION = r'\|'
def t_error(t):
raise TypeError("Unknown text '%s'" % t.value)
def p_multiple(p) :
'''string : SYMBOL SYMBOL
| string SYMBOL
| string string'''
p[0] = (':', p[1], p[2])
def p_union(p) :
'''string : string UNION string'''
p[0] = ('|', p[1], p[3])
def p_star(p) :
'''string : string STAR'''
p[0] = ('*', p[1])
def p_brackets(p) :
'''string : LBRACKET string RBRACKET'''
p[0] = p[2]
def p_symbol(p) :
'''string : SYMBOL'''
p[0] = p[1]
def p_error(p):
print ("Syntax error at '%s'" % p.value)
lex.lex()
yacc.yacc()
lex.input("(a|b*)abc")
parsed = yacc.parse(RE)
[YACC的可能的複製 - 無規則的優先級操作者?](http://stackoverflow.com/questions/40754644/yacc-precedence-of-a-rule-with-no-operator) – rici