#!/usr/bin/env python # coding:utf-8 import re def dealwith(express): express.replace('+-','-') express.replace('--','+') return express def col_suanshu(exp): if '/' in exp: a,b = exp.split('/') return str(float(a)/float(b)) if '*' in exp: a,b = exp.split('*') return str(float(a)*float(b)) def get_no_barcate(express): express =express.strip('()') print('>>>',express) while True: ret = re.search("-?\d+\.?\d*[*/]-?\d+\.?\d*",express) if ret : res = col_suanshu(ret.group()) express = express.replace(ret.group(),'+'+res) print('表达式',express) express = dealwith(express) else : ret = re.findall('-?\d+\.?\d*',express) sum = 0 for i in ret: sum += float(i) return str(sum) express = '1 -2* ((60-30 +(-40/5) *(9-2*5/3 +7 /3*99 /4*2998 +10 *568 /14))-(-4*3)/(16-3*2))' new_express = express.replace(' ','') print(new_express) print('正确的运算结果',eval(new_express)) while True: ret = re.search('\([^()]+\)',new_express) # print(ret.group()) #print(ret.group()) if ret: barcate_sum = get_no_barcate(ret.group()) print('返回值',barcate_sum) new_express =new_express.replace(ret.group(),barcate_sum) new_express= dealwith(new_express) else : sum = get_no_barcate(new_express) print(sum) break