转换ast.数字到小数.十进制表示 python 中的精度



我目前正在编写一个解析器来解析简单的算术公式:只需要(并限制(支持+-*/的数字和变量。例如:

100.50*num*discount

它基本上用于计算产品价格。

这是用python编写的,为了

简单起见,我只想使用python自己的解析器。这个想法是首先将输入解析为 ast,然后在 ast 上行走以将 ast 的节点类型限制在一个小子集中,例如:ast.BinOpast.Addast.Numast.Name等等......

目前它运行良好,除了 ast 中的浮点数不精确。所以我想将ast的ast.Num节点转换为一些ast.Call(func=ast.Name(id='Decimal'), ...)。但问题是:ast.Num只包含一个n字段,即已经解析的浮点数。而且在源代码中获取原始数字文字并不容易:如何获取与Python AST节点对应的源代码?

有什么建议吗?

我建议采用两步法:第一步,使用 Python 的 tokenize 模块将源中的所有浮点数字文字转换为 'Decimal(my_numeric_literal)' 形式的字符串。然后,您可以按照建议的方式处理 AST。

在标记化模块文档中甚至还有第一步的配方。为了避免仅链接答案,以下是该配方中的代码(以及配方本身缺少的必要导入(:

from cStringIO import StringIO
from tokenize import generate_tokens, untokenize, NAME, NUMBER, OP, STRING
def is_float_literal(s):
    """Identify floating-point literals amongst all numeric literals."""
    if s.endswith('j'):
        return False  # Exclude imaginary literals.
    elif '.' in s:
        return True  # It's got a '.' in it and it's not imaginary.
    elif s.startswith(('0x', '0X')):
        return False  # Must be a hexadecimal integer.
    else:
        return 'e' in s  # After excluding hex, 'e' must indicate an exponent.
def decistmt(s):
    """Substitute Decimals for floats in a string of statements.
    >>> from decimal import Decimal
    >>> s = 'print +21.3e-5*-.1234/81.7'
    >>> decistmt(s)
    "print +Decimal ('21.3e-5')*-Decimal ('.1234')/Decimal ('81.7')"
    >>> exec(s)
    -3.21716034272e-007
    >>> exec(decistmt(s))
    -3.217160342717258261933904529E-7
    """
    result = []
    g = generate_tokens(StringIO(s).readline)   # tokenize the string
    for toknum, tokval, _, _, _  in g:
        if toknum == NUMBER and is_float_literal(tokval):
            result.extend([
                (NAME, 'Decimal'),
                (OP, '('),
                (STRING, repr(tokval)),
                (OP, ')')
            ])
        else:
            result.append((toknum, tokval))
    return untokenize(result)

原始配方通过检查值中是否存在'.'来标识浮点文本。这并不完全是防弹的,因为它排除了像'1e10'这样的文字,并包括像1.0j这样的虚构文字(你可能想要排除(。我已经在上面的is_float_literal中用我自己的版本替换了该支票。

在您的示例字符串上尝试此操作,我得到:

>>> expr = '100.50*num*discount'
>>> decistmt(expr)
"Decimal ('100.50')*num *discount "

。您现在可以像以前一样解析为 AST 树:

>>> tree = ast.parse(decistmt(expr), mode='eval')
>>> # walk the tree to validate, make changes, etc.
... 
>>> ast.dump(tree)
"Expression(body=BinOp(left=BinOp(left=Call(func=Name(id='Decimal', ...

最后评估:

>>> from decimal import Decimal
>>> locals = {'Decimal': Decimal, 'num': 3, 'discount': Decimal('0.1')}
>>> eval(compile(tree, 'dummy.py', 'eval'), locals)
Decimal('30.150')

最新更新