2017-05-07 88 views
2

我正在写一个程序,其中一个公式输入为一个字符串,然后评估。到目前为止,我已经想出了这一点:安全评估简单的字符串公式

test_24_string = str(input("Enter your answer: ")) 
test_24 = eval(test_24_string) 

我两者都需要这个公式的字符串版本和评估版本。但是,eval是一个非常危险的功能。但使用int()不起作用,因为它是一个等式。是否有一个Python函数会从字符串中评估数学表达式,就像输入一个数字一样?

回答

3

一种方法是使用。它主要用于优化(和多线程)操作的模块,但它也可以处理数学Python表达式:

>>> import numexpr 
>>> numexpr.evaluate('2 + 4.1 * 3') 
array(14.299999999999999) 

您可以拨打.item对结果得到一个蟒蛇般类型:

>>> numexpr.evaluate('17/3').item() 
5.666666666666667 

这是一个第三方扩展模块,因此它可能在这里完全过度使用,但它比eval更安全并支持相当多的功能(包括numpymath操作)。如果还支持“变量替换”:

>>> b = 10 
>>> numexpr.evaluate('exp(17)/b').item() 
2415495.27535753 

一个与Python标准库的方式,虽然很有限,是ast.literal_eval。它适用于Python中最基本的数据类型和面值:

>>> import ast 
>>> ast.literal_eval('1+2') 
3 

但失败,像更复杂的表达式:

>>> ast.literal_eval('import os') 
SyntaxError: invalid syntax 

>>> ast.literal_eval('exec(1+2)') 
ValueError: malformed node or string: <_ast.Call object at 0x0000023BDEADB400> 

不幸的是,除了+-任何运营商是不可能的:

>>> ast.literal_eval('1.2 * 2.3') 
ValueError: malformed node or string: <_ast.BinOp object at 0x0000023BDEF24B70> 

我复制了包含支持类型的部分文档:

Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

+2

够奇怪的,但是'literal_eval'仅支持'和'-',只有在整数'+。其他操作符生成相同的“格式错误...”错误。测试py3.5。 – robyschek

+0

@robyschek我无法重现与浮动失败('ast.literal_eval('1.2 + 2.3')'工作正常)。但你说得对,并非所有的运营商都有可能。我添加了另一种方式 - 实现(很多)更多功能。 – MSeifert

+0

@MSeifert安装了'numpy'。在导入'numpy'和'numexpr'之后,它会显示'ModuleNotFoundError:No module named'numexpr''。我试过重新安装。 – Aamri

1

编写后缀表达式求值器并不难。以下是一个工作示例。 (也available在github上。)

import operator 
import math 

_add, _sub, _mul = operator.add, operator.sub, operator.mul 
_truediv, _pow, _sqrt = operator.truediv, operator.pow, math.sqrt 
_sin, _cos, _tan, _radians = math.sin, math.cos, math.tan, math.radians 
_asin, _acos, _atan = math.asin, math.acos, math.atan 
_degrees, _log, _log10 = math.degrees, math.log, math.log10 
_e, _pi = math.e, math.pi 
_ops = {'+': (2, _add), '-': (2, _sub), '*': (2, _mul), '/': (2, _truediv), 
     '**': (2, _pow), 'sin': (1, _sin), 'cos': (1, _cos), 'tan': (1, _tan), 
     'asin': (1, _asin), 'acos': (1, _acos), 'atan': (1, _atan), 
     'sqrt': (1, _sqrt), 'rad': (1, _radians), 'deg': (1, _degrees), 
     'ln': (1, _log), 'log': (1, _log10)} 
_okeys = tuple(_ops.keys()) 
_consts = {'e': _e, 'pi': _pi} 
_ckeys = tuple(_consts.keys()) 


def postfix(expression): 
    """ 
    Evaluate a postfix expression. 

    Arguments: 
     expression: The expression to evaluate. Should be a string or a 
        sequence of strings. In a string numbers and operators 
        should be separated by whitespace 

    Returns: 
     The result of the expression. 
    """ 
    if isinstance(expression, str): 
     expression = expression.split() 
    stack = [] 
    for val in expression: 
     if val in _okeys: 
      n, op = _ops[val] 
      if n > len(stack): 
       raise ValueError('not enough data on the stack') 
      args = stack[-n:] 
      stack[-n:] = [op(*args)] 
     elif val in _ckeys: 
      stack.append(_consts[val]) 
     else: 
      stack.append(float(val)) 
    return stack[-1] 

用法:

In [2]: from postfix import postfix 

In [3]: postfix('1 2 + 7 /') 
Out[3]: 0.42857142857142855 

In [4]: 3/7 
Out[4]: 0.42857142857142855