import re def cal_mini_exp(mini): # ‘40/5‘ ‘2*5‘ if ‘*‘ in mini: num1,num2 = mini.split(‘*‘) return str(float(num1)*float(num2)) elif ‘/‘ in mini: num1, num2 = mini.split(‘/‘) return str(float(num1) / float(num2)) def dealwith(exp): exp = exp.replace(‘--‘,‘+‘) exp = exp.replace(‘+-‘,‘-‘) exp = exp.replace(‘-+‘,‘-‘) exp = exp.replace(‘++‘,‘+‘) return exp def calculate(son_exp): ‘‘‘ 计算没有括号的表达式的结果 (9-2*5/3+7/3*99/4*2998+10*568/14) ‘‘‘ son_exp = son_exp.strip(‘()‘) while True: # ‘完成了一个表达式中所有乘除法的计算‘ ret = re.search(‘\d+\.?\d*[*/]-?\d+\.?\d*‘,son_exp) #(9-3.33333+7/3*99/4*2998+10*568/14) if ret: mini_exp = ret.group() #2*5 10/3 res = cal_mini_exp(mini_exp) # 2*5 3.33333 son_exp = son_exp.replace(mini_exp,res,1) #(9-3.33333+7/3*99/4*2998+10*568/14) else:break son_exp = dealwith(son_exp) # 整理表达式中的符号 ret_l = re.findall(‘[+-]?\d+\.?\d*‘,son_exp) sum = 0 for i in ret_l: sum += float(i) return str(sum) def remove_bracket(express): while True: ret = re.search(‘\([^()]+\)‘, express) # 是否匹配上的对象 if ret: son_exp = ret.group() # 子表达式 (-40/5) # 计算 计算乘除法 再计算加减法 ret = calculate(son_exp) # -8 express = express.replace(son_exp, ret, 1) else: break return express def main(express): express = express.replace(‘ ‘,‘‘) express = remove_bracket(express) ret = calculate(express) print(ret) if __name__ == ‘__main__‘: express = "-1 + 2 * ((60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )" main(express)