2017-05-07 84 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