经过2天的长时间的战斗,python计算器终于完成了。
1 import re 2 val="1-2*((60-30*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))" 3 def chen(arg): 4 f = arg 5 # print (f) 6 if "*" in arg or "/" in arg: 7 '''如果包含*号或者除好则进如该方法''' 8 b2_2 = re.search("d+.?d*[*/]+-?d+.?d*", arg) 9 m = b2_2.group() 10 k = re.split("([*/])", m, 1) 11 kn = k[0] + '\' + k[1] + k[2] 12 if k[1] == '*': 13 new_a = float(k[0]) * float(k[2]) 14 f = re.sub(kn, str(new_a), arg) 15 new_z = chen(f) 16 return new_z 17 elif k[1] == '/': 18 new_a = float(k[0]) / float(k[2]) 19 f = re.sub(kn, str(new_a), arg) 20 new_z = chen(f) 21 return new_z 22 elif re.match("-+d+.?d*[+-]+d+.?d*",arg): 23 '''如果是负数的减法则进如该方法''' 24 m = re.search("-+d+.?d*[+-]+d+.?d*", arg).group() 25 k = re.split("([+-])", m, 1) 26 kt =re.split("([+-])", m, 2) 27 kn = k[0] + '\' + k[1] + k[2] 28 aa = "%s%s" %(kt[1],kt[2]) 29 if kt[3] == '-': 30 new_a = float(aa) - float(kt[4]) 31 f = re.sub(kn, str(new_a), arg) 32 new_z = chen(f) 33 return new_z 34 elif re.search("d+.?d*[+-]+d+.?d*", arg): 35 '''如果是 加号和减号则进如该方法''' 36 # b2_2 = re.search("d+.*d*[+-]+d+.*d*", arg) 37 b2_2 = re.search("d+.?d*[+-]+d+.?d*", arg) 38 m = b2_2.group() 39 k = re.split("([+-])", m, 1) 40 kn = k[0] + '\' + k[1] + k[2] 41 # print (k) 42 if k[1] == '+': 43 new_a = float(k[0]) + float(k[2]) 44 f = re.sub(kn, str(new_a), arg) 45 new_z = chen(f) 46 return new_z 47 elif k[1] == '-': 48 new_a = float(k[0]) - float(k[2]) 49 f = re.sub(kn, str(new_a), arg) 50 new_z = chen(f) 51 return new_z 52 return f 53 54 #b = re.split("(([^()]+))",val,1) 55 while True: 56 b = re.split("(([^()]+))", val, 1) 57 if len(b) == 3: 58 # print (b) 59 a1,a2,a3=b 60 chen1=chen(a2) 61 val = "%s%s%s" %(a1,chen1,a3) 62 else: 63 val=chen(val) 64 print (val) 65 break