我有一个字典,其中包含通过Web应用程序提供的一组键值: 我想处理用户提供的公式,如: ((值1 +值3)/ VALUE4)* 100
最简单的方法是使公式计算出匹配值与字典中的值?
考虑这个例子:
#!/usr/bin/python
values={'value1':10,'value2':1245,'value3':674365,'value4':65432,'value5':131}
formula=raw_input('Please enter formula:')
如果我提供公式'((value1 + value3)/ value4)* 100',我如何将value1等映射到字典中的map1并计算结果?
干杯,
答案 0 :(得分:6)
eval
可用于执行恶意代码。
您相信您的用户吗?如果是这样,您可以将values
作为全局字典传递给eval
使用。因此,eval
可以直接评估用户公式,而无需任何其他字符串操作:
values={'value1':10,'value2':1245,'value3':674365,'value4':65432,'value5':131}
formula=raw_input('Please enter formula:')
values=eval(formula,values)
print(values)
如果您不信任潜在用户,可以使用pyparsing: 以下是Paul McGuire的numeric expression parser, fourFn.py,包含在一个类中以便于使用。
utils_parse_numeric.py:
from __future__ import division
from pyparsing import (Literal,CaselessLiteral,Word,Combine,Group,Optional,
ZeroOrMore,Forward,nums,alphas,oneOf)
import math
import operator
class NumericStringParser(object):
'''
Most of this code comes from the fourFn.py pyparsing example
'''
def pushFirst(self, strg, loc, toks ):
self.exprStack.append( toks[0] )
def pushUMinus(self, strg, loc, toks ):
if toks and toks[0]=='-':
self.exprStack.append( 'unary -' )
def __init__(self):
"""
expop :: '^'
multop :: '*' | '/'
addop :: '+' | '-'
integer :: ['+' | '-'] '0'..'9'+
atom :: PI | E | real | fn '(' expr ')' | '(' expr ')'
factor :: atom [ expop factor ]*
term :: factor [ multop factor ]*
expr :: term [ addop term ]*
"""
point = Literal( "." )
e = CaselessLiteral( "E" )
fnumber = Combine( Word( "+-"+nums, nums ) +
Optional( point + Optional( Word( nums ) ) ) +
Optional( e + Word( "+-"+nums, nums ) ) )
ident = Word(alphas, alphas+nums+"_$")
plus = Literal( "+" )
minus = Literal( "-" )
mult = Literal( "*" )
div = Literal( "/" )
lpar = Literal( "(" ).suppress()
rpar = Literal( ")" ).suppress()
addop = plus | minus
multop = mult | div
expop = Literal( "^" )
pi = CaselessLiteral( "PI" )
expr = Forward()
atom = ((Optional(oneOf("- +")) +
(pi|e|fnumber|ident+lpar+expr+rpar).setParseAction(self.pushFirst))
| Optional(oneOf("- +")) + Group(lpar+expr+rpar)
).setParseAction(self.pushUMinus)
factor = Forward()
factor << atom + ZeroOrMore( ( expop + factor ).setParseAction( self.pushFirst ) )
term = factor + ZeroOrMore( ( multop + factor ).setParseAction( self.pushFirst ) )
expr << term + ZeroOrMore( ( addop + term ).setParseAction( self.pushFirst ) )
self.bnf = expr
epsilon = 1e-12
self.opn = { "+" : operator.add,
"-" : operator.sub,
"*" : operator.mul,
"/" : operator.truediv,
"^" : operator.pow }
self.fn = { "sin" : math.sin,
"cos" : math.cos,
"tan" : math.tan,
"abs" : abs,
"trunc" : lambda a: int(a),
"round" : round,
"sgn" : lambda a: abs(a)>epsilon and cmp(a,0) or 0}
def evaluateStack(self, s ):
op = s.pop()
if op == 'unary -':
return -self.evaluateStack( s )
if op in "+-*/^":
op2 = self.evaluateStack( s )
op1 = self.evaluateStack( s )
return self.opn[op]( op1, op2 )
elif op == "PI":
return math.pi # 3.1415926535
elif op == "E":
return math.e # 2.718281828
elif op in self.fn:
return self.fn[op]( self.evaluateStack( s ) )
elif op[0].isalpha():
return 0
else:
return float( op )
def eval(self,num_string,parseAll=True):
self.exprStack=[]
results=self.bnf.parseString(num_string,parseAll)
val=self.evaluateStack( self.exprStack[:] )
return val
然后你的脚本可以这样做:
import re
import utils_parse_numeric as upn
my_dict={
'number1':54,
'number2':1234,
'number3':778,
'number25':2109}
这使用re
模块将my_dict [“numberXXX”]替换为'numberXXX':
def callback(match):
num=match.group(1)
key='number{0}'.format(num)
val=my_dict[key]
return str(val)
astr='((number1+number3)/number2)*100'
astr=re.sub('number(\d+)',callback,astr)
以下是NumericStringParser如何用于安全地评估数值表达式:
nsp=upn.NumericStringParser()
result=nsp.eval(astr)
print(result)
这比使用eval更安全。所有无效表达式都会引发pyparsing.ParseException。
答案 1 :(得分:0)
验证公式和数字值(通过正则表达式后)后,您可以执行以下操作:
arr = {'num1':4, 'num2':5, 'num3':7}
formula = '(num1+num2)*num3'
for key, val in arr.items():
formula = formula.replace(key, str(val))
res = eval(formula)
print res
答案 2 :(得分:0)
感谢所有输入。我个人发现lacopo的答案最适合我的情况。
以下是对解决方案的粗略概念:
import sys
values={'one':10,'two':1245,'three':674365,'four':65432,'five':131}
print str(values)
formula=raw_input('Please enter formula:')
for key, val in values.items():
formula = formula.replace(key, str(val))
whitelist=[ '+','-','/','*','^','(',')' ]
to_evaluate=re.findall('\D',formula)
to_evaluate=list(set(to_evaluate))
for element in to_evaluate:
if not element in whitelist:
print "Formula contains an invalid character: "+str(element)
sys.exit(1)
print eval(formula)