You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python SLY开发词法分析器时如何区分识别int与float数据类型

问题原因及修复方案

1. 正则表达式错误

你当前写的FLOAT匹配正则r'\d+.\d+'中,.是正则元字符,会匹配任意单个字符,若要匹配字面量小数点,必须加反斜杠转义,正确写法为r'\d+\.\d+'。

2. FLOAT处理逻辑错误

你在FLOAT处理函数中把匹配到的字符串转成了int类型,会直接报错或丢失小数精度,需要改为转成float类型。

3. 规则顺序错误

Sly的词法规则会按代码定义的先后顺序匹配,必须把FLOAT规则放在INT规则前面,否则输入1.23时会先匹配到INT规则提取出1作为INT token,剩下的.23无法正常识别。

完整可运行示例代码

from sly import Lexer

class NumberLexer(Lexer):
    tokens = { INT, FLOAT }
    # 忽略输入中的空格、制表符
    ignore = ' \t'

    @_(r'\d+\.\d+')
    def FLOAT(self, t):
        t.value = float(t.value)
        return t

    @_(r'\d+')
    def INT(self, t):
        t.value = int(t.value)
        return t

# 测试效果
if __name__ == '__main__':
    lexer = NumberLexer()
    input_text = '123 1.23'
    for index, token in enumerate(lexer.tokenize(input_text)):
        print(f"TOKEN:{token.value}; ID:{index}; TYPE:{token.type.lower()}-datatype")

运行上述代码即可直接得到你期望的输出效果。

内容的提问来源于stack exchange,提问作者Muhammad Hammad Hassan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 15:39:03