1
我正在用python PLY編寫一個非常簡單的解析器。它主要是做的工作,但對於許多輸入行,我從yacc
得到一個語法錯誤。這裏是詞法分析器和解析器代碼,稍加修改,以方便檢測:
tokens = ('VAR', 'NUMBER', 'CLOSE', 'JUNK')
# Tokens
t_VAR = r'%[mM]\['
t_CLOSE = r'\]'
t_JUNK = r'.'
# Ignored characters
t_ignore = " \t\r"
def t_NUMBER(t):
r'\d+'
try:
t.value = int(t.value)
except ValueError:
print("Integer value too large %d", t.value)
t.value = 0
return t
def t_newline(t):
r'\n+'
t.lexer.lineno += t.value.count("\n")
def t_error(t):
print("Illegal character '%s'" % t.value[0])
t.lexer.skip(1)
# Build the lexer
import ply.lex as lex
lex.lex()
# Parsing rules
def p_statement(p):
'''statement : field'''
try:
print p[1]
except IndexError:
pass
def p_trash(p):
'''statement : JUNK'''
pass
def p_field(p):
'''field : VAR NUMBER CLOSE'''
#print p[1], p[2], p[3]
p[0] = p[2]
def p_error(p):
print("Syntax error at '%s'" % repr(p)) #p.value)
import ply.yacc as yacc
yacc.yacc()
對於樣品:yacc.parse('.set %m[702] $substr($currentlength,2,$currentpg)')
其給出作爲輸出:
Syntax error at 'LexToken(JUNK,'s',1,1)'
Syntax error at 'LexToken(JUNK,'$',1,13)'
它應該輸出702
只。
哦咄!我知道這是我忘記的簡單事情。 – 2012-01-28 15:29:20