用正则表达式实现 计算器
Posted saolv
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用正则表达式实现 计算器相关的知识,希望对你有一定的参考价值。
#!/usr/bin/env python # coding:utf-8 import re def dealwith(express): express.replace(‘+-‘,‘-‘) express.replace(‘--‘,‘+‘) return express def col_suanshu(exp): if ‘/‘ in exp: a,b = exp.split(‘/‘) return str(float(a)/float(b)) if ‘*‘ in exp: a,b = exp.split(‘*‘) return str(float(a)*float(b)) def get_no_barcate(express): express =express.strip(‘()‘) print(‘>>>‘,express) while True: ret = re.search("-?d+.?d*[*/]-?d+.?d*",express) if ret : res = col_suanshu(ret.group()) express = express.replace(ret.group(),‘+‘+res) print(‘表达式‘,express) express = dealwith(express) else : ret = re.findall(‘-?d+.?d*‘,express) sum = 0 for i in ret: sum += float(i) return str(sum) express = ‘1 -2* ((60-30 +(-40/5) *(9-2*5/3 +7 /3*99 /4*2998 +10 *568 /14))-(-4*3)/(16-3*2))‘ new_express = express.replace(‘ ‘,‘‘) print(new_express) print(‘正确的运算结果‘,eval(new_express)) while True: ret = re.search(‘([^()]+)‘,new_express) # print(ret.group()) #print(ret.group()) if ret: barcate_sum = get_no_barcate(ret.group()) print(‘返回值‘,barcate_sum) new_express =new_express.replace(ret.group(),barcate_sum) new_express= dealwith(new_express) else : sum = get_no_barcate(new_express) print(sum) break
以上是关于用正则表达式实现 计算器的主要内容,如果未能解决你的问题,请参考以下文章