“SyntaxError:无法构建词法分析器”?

时间:2014-06-27 19:33:08

标签: python regex python-3.x lexer ply

这是我的代码:

import ply.lex as lex

tokens = (
    'LANGLE', # <
    'LANGLESLASH', # </
    'RANGLE', # >
    'EQUAL', # =
    'STRING', # "hello"
    'WORD') # Welcome!

state = (
("htmlcomment", "exclusive"),
)

t_ignore = ' '

def t_htmlcomment(token):
    r'<!--'
    token.lexer.begin('htmlcomment')

def t_htmlcomment_end(token):
    r'-->'
    token.lexer.lineno += token.value.count('\n')
    token.lexer.begin('INITIAl')

def t_htmlcomment_error(token):
    token.lexer.skip(1)

def t_newline(token):
    r'\n'
    token.lexer.lineno += 1
    pass

def t_LANGLESLASH(token):
    r'</'
    return token

def t_LANGLE(token):
    r'<'
    return token

def t_RANGLE(token):
    r'>'
    return token

def t_EQUAL(token):
    r'='
    return token

def t_STRING(token):
    r'"[^"]*"'
    token.value = token.value[1:-1] # dropping off the double quotes
    return token

def t_WORD(token):
    r'[^ <>\n]+'
    return token

webpage = "This is <b>my</b> webpage"
htmllexer = lex.lex()
htmllexer.input(webpage)
while True:
    tok = htmllexer.token()
    if not tok: break
    print(tok)

当我运行它时出现错误:

Traceback (most recent call last):
  File "/home/******/Documents/pro/main.py", line 62, in <module>
    htmllexer = lex.lex()
  File "/usr/lib/python2.7/dist-packages/ply/lex.py", line 901, in lex
    raise SyntaxError("Can't build lexer")
SyntaxError: Can't build lexer

我认为问题在于:

state = (
("htmlcomment", "exclusive"),
)

但是我无法解决它。

有没有人有任何建议我该如何解决?

感谢您的帮助!

0 个答案:

没有答案