标签:color group eva expr 格式化 lse one add port
def calc_multi_div(expression): if "*" in expression: a,b=expression.split(‘*‘) return float(a)*float(b) if "/" in expression: a, b = expression.split(‘/‘) return float(a)/float(b) def calc_sub_add(expression): if "+" in expression: a, b = expression.split(‘+‘) return float(a) + float(b) if expression[0] == ‘-‘: ##计算加减运算时,需要注意被减数为负值的减法运算 a,b,c =expression.split(‘-‘) return -float(b)-float(c) if "-" in expression: a, b = expression.split(‘-‘) return float(a) - float(b) def exp_fmt(expression): ###注意表达式的格式化 while re.search(‘[+-]{2,}‘,expression): expression = expression.replace(‘--‘,‘+‘) expression = expression.replace(‘++‘,‘+‘) expression = expression.replace(‘+-‘, ‘-‘) expression = expression.replace(‘-+‘, ‘-‘) return expression def func(regx2,regx3,exp_child): while 1: res0 = re.search(regx2, exp_child) if res0: exp_child = exp_child.replace(str(res0.group()), str(calc_multi_div(res0.group()))) else:break exp_child = exp_fmt(exp_child) while 1: res0 = re.search(regx3, exp_child) if res0: exp_child = exp_child.replace(str(res0.group()), str(calc_sub_add(res0.group()))) else:break return exp_child import re def cal(exp): regx1 = re.compile(‘[(]([-+*/\d+.\d+]*?)[)]‘) ###匹配最内层括号里面的表达式 regx2 = re.compile(‘\d+(\.\d+)?[/*]-?\d+(\.\d+)?‘) ###匹配从左到右第一个*/表达式 regx3 = re.compile(‘[+-]?\d+(\.\d+)?[-+]\d+(\.\d+)?‘) # 匹配加减运算左边第一个+-运算 while 1: old_exp_child = re.search(regx1,exp) if old_exp_child == None: return func(regx2,regx3,exp) exp_child = old_exp_child.group() exp_child = func(regx2, regx3, exp_child) exp_child=exp_child.split(‘(‘)[1].split((‘)‘))[0] exp = exp_fmt(exp.replace(old_exp_child.group(),exp_child)) exp= ‘1 - 2 * ((60-30 +(-40/5) * (9-2*5/-3 + 7/3*99/4*2998 +10* 568/14)) - (-4*3)/(16-3*2))‘ # exp=‘1+2.238-++317+-428-5+6‘ exp = exp.replace(" ","") exp = exp_fmt(exp) print(exp) print(cal(exp)) print(eval(exp))
标签:color group eva expr 格式化 lse one add port
原文地址:https://www.cnblogs.com/funch/p/12824589.html