import re def form_s(s): s = s.replace('++','+') s = s.replace('+-','-') s = s.replace('-+','-') s = s.replace('--','+') return s def mul_sub(s): mul_regular = '[-]?d+.?d*[*/][-]?d+.?d*' n1 = re.search(mul_regular,s) print(n1.group()) while re.search(mul_regular,s): n2=re.search(mul_regular,s).group() if n2.count('*') == 1: x,y = n2.split('*') result = str(float(x)*float(y)) s = s.replace(n2,result) s=form_s(s) if n2.count('/') ==1: x,y =n2.split('/') #print(x,y) result = float(x)/float(y) result = str(result) s=s.replace(n2,result) s=form_s(s) return s def add_sub(s): add_regular = '-?d+.?d*[-+]d+.?d*' #n1 = re.search(add_regular,s) #print(n1.group()) while re.search(add_regular,s): n2 = re.search(add_regular,s).group() if n2.count('+') == 1: x,y =n2.split('+') result =str(float(x)+float(y)) s = s.replace(n2,result) s = form_s(s) if n2.count('-') == 1: x,y = n2.split('-') result = str(float(x)-float(y)) s = s.replace((n2,result)) s = form_s(s) return s if __name__ == '__main__': while 1: s=input("请输入计算式(退出按q):") if s == 'q': exit() else: print('计算式为',s) print('eval result = ',eval(s)) print('规范式子为:',form_s(s)) #m1 = re.search('([^()]+)',s) #print(m1) while re.search('([^()]+)',s): m2 = re.search('([^()]+)',s).group() re_str = mul_sub(m2) #print(re_str) re_str = add_sub(re_str) #print(re_str) s = form_s(s.replace(m2,re_str[1:-1])) print(s) re_str = mul_sub(s) re_str = add_sub(re_str) #print(re_str) #s= form_s(s.replace(s,re_str[1:-1])) print('结果是:',re_str)