使用正则表达式实现计算器:
express = '1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
#计算器 import re #计算乘除法 def cal_mimi_exp(mini): if '*' in mini: num1,num2 = mini.split('*') return str(float(num1) * float(num2))# 为了后面的替换,在这里把int转为str 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): ''' 计算没有括号的表达式的结果 ''' son_exp = son_exp.strip('()')#去掉两边的括号 #计算乘除法 while True: ret = re.search('d+.?d*[*/]-?d+.?d*',son_exp)#匹配一个乘号或除号 if ret: mini_exp = ret.group() res = cal_mimi_exp(mini_exp)#计算乘除法 son_exp = son_exp.replace( mini_exp,res,1) else:break son_exp = dealwith(son_exp) # 整理表达式中的加减符号 # 计算加减法 res = re.findall('[+-]?d+.?d*',son_exp) sum = 0 for i in res: sum += float(i) return str(sum) def remove_bracket(express): while True: ret = re.search('([^()]+)', express) # 返回是否匹配上的对象 if ret: son_exp = ret.group() # 子表达式 ret = calculate(son_exp) 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('***result***', 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) #>>>***result*** -2776672.6952380957 print(eval('-1 + 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )')) #>>>-2776672.6952380957
代码优化:
# -*- coding: utf-8 -*- # Date: 2018/5/11 import re def cal_mini_exp(mini): ''' 乘除计算 :param mini: :return: ''' if '*' in mini: val1, val2 = mini.split('*') return str(float(val1) * float(val2)) # 为了后面的替换,在这里把int转为str elif '/' in mini: val1, val2 = mini.split('/') return str(float(val1) / float(val2)) def dealwith(exp): ''' 整理表达式内的符号 :param exp: :return: ''' exp = exp.replace('--', '+').replace('+-', '-').replace('-+', '-').replace('++', '+') return exp def calculate(son_exp): ''' 计算没有括号的表达式 :return: ''' son_exp = son_exp.strip('()') while 1: # 完成了表达式中乘除法的计算 ret = re.search('d+.?d*[*/]-?d+.?d*', son_exp) if ret: mini_exp = ret.group() res = cal_mini_exp(mini_exp) # 乘除计算结果并返回结果 son_exp = son_exp.replace(mini_exp, res, 1) else: break son_exp = dealwith(son_exp) # 整理那些加加减减去重 3-+1--2之类的 # 最后的加减法计算 res = re.findall('[+-]?d+.?d*', son_exp) sum = 0 for i in res: sum += float(i) return str(sum) def remove_bracket(express): ''' 去括号 把内部不再有小括号的表达式匹配出来 :([^()]+) :return: ''' while 1: ret = re.search('([^()]+)', express) # 是否匹配上的对象 if ret: son_exp = ret.group() # 子表达式 # 计算,先乘除后加减 ret = calculate(son_exp) 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__': print('输入计算的内容或输入Q退出'.center(30, '*')) while 1: express = input('please enter: ') if express == 'Q' or express == 'q': break elif '/0' in express: print('0不能为被除数') elif express.count('(') != express.count(')') or '=' in express: print('表达式错误,请重新输入') else: main(express)