代码比较low,有时间在更新。
当时初学只是为了实现。
#实现加减乘除以及括号优先级解析)) import re s = "1-2*((60-30+(-40/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))" # s = "1-2*((60-30-8*(9-3+146902+405))-(-4*3)/(16-3*2))" print(eval(s)) def retr(str): try: str = str.replace("--", "+") str = str.replace("++", "+") str = str.replace("-+", "-") str = str.replace("+-", "-") except: pass ret = re.search("([^()]+)", str) a = ret.group() print(a) if ret == None: pass else: suan = ret.group() suan = suan.replace("(", "") suan = suan.replace(")", "") return suan,a # def th(str): def hf(str): a = str[:2] if not a.isdigit(): if a == "-+" or a == "+-": str = str.replace(a, "-") return str def jjcc(str): nstr = hf(str) ret = re.search("(.*?d+)(D)(.*?d+)", nstr) # print(ret.group()) a = ret.group(2) c = int(ret.group(1)) b = int(ret.group(3)) if a == "+": end = c + b if a == "-": end = c - b if a == "*": end = c * b if a == "/": end = c / b return end # print(jjcc(suan)) # print(jjcc("-+6*-1")) # while True: # suan, a = retr(s)[0],retr(s)[1] # rep = str(jjcc(suan)) # s = s.replace(a, rep) # print(s) suan, a = retr(s)[0], retr(s)[1] rep = str(jjcc(suan)) s = s.replace(a, rep) # print(s) suan, a = retr(s)[0], retr(s)[1] rep = str(jjcc(suan)) s = s.replace(a, rep) # print(s)