How to process user supplied formulas?

前端 未结 3 497
孤城傲影
孤城傲影 2021-01-16 08:38

I have a dictionary containing a set of key values available through a web application: I want to process user supplied formulas like: ((value1+value3)/value4)*100

W

3条回答
  •  难免孤独
    2021-01-16 08:59

    Thanks for all the input. I personally found that lacopo's answer suites my situation best.

    Here's a rough idea of the solution:

    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)
    

提交回复
热议问题