标签:span imp 运用 pil find 除法 search tor 乘法
import re bracket = re.compile(r‘\([^()]+\)‘) # 寻找最内层括号规则 mul = re.compile(r‘(\d+\.?\d*\*-\d+\.?\d*)|(\d+\.?\d*\*\d+\.?\d*)‘) # 寻找乘法运算规则 div = re.compile(r‘(\d+\.?\d*/-\d+\.?\d*)|(\d+\.?\d*/\d+\.?\d*)‘) # 寻找除法运算规则 add = re.compile(r‘(-?\d+\.?\d*\+-\d+\.?\d*)|(-?\d+\.?\d*\+\d+\.?\d*)‘) # 寻找加法运算规则 sub = re.compile(r‘(-?\d+\.?\d*--\d+\.?\d*)|(-?\d+\.?\d*-\d+\.?\d*)‘) # 寻找减法运算规则 c_f = re.compile(r‘\([^*/]\)‘) # 检查括号内是否运算完毕规则 strip = re.compile(r‘[^(].*[^)]‘) # 脱括号规则 n_md = re.compile(‘\([^*/]+\)‘) res = re.compile(‘([+-]?\d+\.?\d*)‘) ills= re.compile(r‘[^0-9*/+\-\(\)]‘) def Mul(exp): result = re.split(r‘\*‘,mul.search(exp).group()) return exp.replace(mul.search(exp).group(),str(float(result[0])*float(result[1]))) def Div(exp): result = re.split(r‘/‘, div.search(exp).group()) return exp.replace(div.search(exp).group(), str(float(result[0])/ float(result[1]))) def Add_Sub(exp): exp = exp.replace(‘++‘,‘+‘) exp = exp.replace(‘+-‘,‘-‘) exp = exp.replace(‘--‘,‘+‘) exp = exp.replace(‘-+‘,‘-‘) # print(exp) nums = re.findall(‘[+\-]?\d+\.?\d*‘,exp) count = 0 for num in nums: count += float(num) return str(count) # 没有添加用户输入判断 def calculator(): while True: exp = input(‘>>>‘) if exp.strip().upper() == ‘Q‘: print(‘退出程序‘) exit() else: exp = exp.replace(‘ ‘,‘‘) if ills.search(exp): print(‘有非法字符!‘) else: while bracket.search(exp): result = bracket.search(exp).group() print(result) if div.search(result): exp = exp.replace(result,Div(result)) elif mul.search(result): exp = exp.replace(result,Mul(result)) elif n_md.search(result): exp = exp.replace(n_md.search(result).group(),Add_Sub(result)) print(exp) while True: if div.search(exp): result = div.search(exp).group() exp = exp.replace(result,Div(result)) elif mul.search(exp): result = mul.search(exp).group() exp = exp.replace(result,Mul(result)) else: result = Add_Sub(exp) print(‘The answer is: %.2f‘%float(result)) break calculator() # print(1-2*((60-30+(-40/-5+20/4+3*4*5/2)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))-99*2) # print(69*(69+1)*100+2*8)
标签:span imp 运用 pil find 除法 search tor 乘法
原文地址:https://www.cnblogs.com/kuraki/p/9797248.html