python - 数字的 PLY 词法分析器始终返回 double

标签 python lex ply

我在使用以下程序使用 int 和 double 进行 ply lex 时遇到问题。返回 1 的 DOUBLE_VAL,而我期望的是 INT_VAL。在更改 INT_VAL 和 DOUBLE_VAL 函数的顺序时,我在小数点上收到错误。我该如何解决这些问题?

tokens = (
'VERSION',
'ID',
'INT_VAL',
'DOUBLE_VAL'
)

t_ignore = ' \t'
def t_VERSION(t):
    r'VERSION'
    return t

def t_DOUBLE_VAL(t):
    '[-+]?[0-9]+(\.[0-9]+)?([eE][-+]?[0-9]+)?'
    return t

def t_INT_VAL(t):
    r'[-+]?[0-9]+'
    return t

def t_ID(t):
    r'[a-zA-Z_]([_a-zA-Z0-9]*[a-zA-Z0-9])?'
    return t

def t_error(t):
    print "Error: ", t
    #exit(-1)

import ply.lex as lex
lexer = lex.lex()
lexer.input('VERSION 1 4.0')
while True:
    tok = lexer.token()
    if not tok: break
    print tok

最佳答案

您的语法正在将整数与 t_DOUBLE_VAL 进行匹配。将 t_DOUBLE_VAL 的表达式更改为仅在存在小数点时匹配:

def t_DOUBLE_VAL(t):
    '[-+]?[0-9]+(\.([0-9]+)?([eE][-+]?[0-9]+)?|[eE][-+]?[0-9]+)'
    return t

关于python - 数字的 PLY 词法分析器始终返回 double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19821234/

相关文章:

python - 在 Windows 上创建 python 3.5 exe

c++ - 在flex中匹配C风格多行注释的最佳解决方案?

c - 如何设定规则的优先级?

python - 使用 PLY 解析标记

python - PLY:C 解析器中的 token 移位问题

python - VBA 的上下文无关语法

Python浮点到字符串,只有 "dotted notation"?

python - 如何正确使用反斜杠在 if 语句中续行?

python - Google 平台上的 Composer 不适用于 Python 3

lex - 使用 Lex/Yacc 识别汉字中的标识符