python 利用正則實現簡易計算器

#-*-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('+',''))


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章