python 利用正则实现简易计算器
2017-10-11 23:05
197 查看
#-*-coding:utf-8-*- #__author:martin #date:2017/10/11 import re def f_string(s): s = s.replace(' ','') s = s.replace('++', '+') s = s.replace('--', '+') s = s.replace('+-', '-') return s def cal_mul_div(s): #(33+4*5.5+10/2) while re.search('\d+\.?\d*[*/]\d+\.?\d*',s) : ret = re.search('\d+\.?\d*[*/]\d+\.?\d*',s).group() if ret.count('*'): x, y = re.split('[*]', ret) mul = float(x) * float(y) s =s.replace(ret,str(mul)) if ret.count('/'): x, y = re.split('[/]', ret) mul = float(x) / float(y) s =s.replace(ret,str(mul)) return s def cal_plus_sub(s): #(33+22.0-5.0+8-5+9) while re.search('[\-]?\d+\.?\d*[+][\-]?\d+\.?\d*', s): ret = re.search('[\-]?\d+\.?\d*[+][\-]?\d+\.?\d*', s).group() x, y = re.split('[+]', ret) add = str(float(x)+float(y)) s = s.replace(ret,'+'+add) s =f_string(s) while re.search('[\-]?\d+\.?\d*[-][\-]?\d+\.?\d*', s): ret = re.search('[\-]?\d+\.?\d*[-][\-]?\d+\.?\d*', s).group() numbers = re.split('[-]', ret) if len(numbers) == 3: result =0 for i in numbers: if i: result -= float(i) else: x,y = numbers result = float(x)-float(y) s = s.replace(ret,'+'+str(result)) s = f_string(s) return s exp = '(1+(3*4)+2+(4*5)-100)' while exp.count('(') > 0: ret = re.search('\([^()]+\)', exp).group() replace_str = cal_mul_div(ret) replace_str = cal_plus_sub(replace_str) exp = exp.replace(ret,replace_str[1:-1]) print(exp.replace('+',''))
相关文章推荐
- Python利用正则表达式实现计算器算法思路解析
- 利用正则实现彩色控制台输出
- 利用 Python 实现多线程多任务提交 - matlab 函数示例
- 【python】利用http的POST请求实现自动翻译机
- Python利用operator模块实现对象的多级排序详解
- 利用python正则表达式 遍历目录后取出目录树中的所有特定目录
- python中利用itchat实现自动回复
- 利用python实现电影推荐
- C#利用正则表达式实现字符串搜索
- C#中利用正则表达式实现字符串搜索
- 利用Python实现卷积神经网络的可视化
- Python下利用PIL实现可设定阈值的二值图像转换
- 利用python opencv实现图像自适应二值化
- Python基于正则表达式实现检查文件内容的方法【文件检索】
- C#中利用正则表达式实现字符串搜索
- 在Win7环境下,利用SWIG实现Python调用C的方法
- 利用python实现微信小程序游戏跳一跳详细教程
- 利用Python中SocketServer 实现客户端与服务器间非阻塞通信
- 利用Python实现:将图片转化为Excel并保存
- Python实现的正则表达式文本查找工具