python3 re模块,正则表达式方式实现简单加减乘除计算器

import re
#加法
def plus(s):
    if re.search("^\d+[.]?\d*\+\d+[.]?\d*",s) != None:
        str_re = re.search("\d+[.]?\d*\+\d+[.]?\d*", s).group()
        x = float(re.search("^\d+[.]?\d*",str_re).group())
        y = float(re.search("\d+[.]?\d*$",str_re).group())
        result = str('{:.15f}'.format(x+y))
        return result
    elif re.search("^\-\d+[.]?\d*\+",s) != None:
        str_re = re.search("^\-\d+[.]?\d*\+\d+[.]?\d*", s).group()
        x = float(re.search("^\-\d+[.]?\d*", str_re).group())
        y = float(re.search("\d+[.]?\d*$", str_re).group())
        result = str('{:.15f}'.format(x+y))
        return  result
#减法
def minus(s):
    if re.search("^\d+[.]?\d*\-\d+[.]?\d*",s) != None:
        str_re = re.search("\d+[.]?\d*\-\d+[.]?\d*", s).group()
        x = float(re.search("^\d+[.]?\d*",str_re).group())
        y = float(re.search("\d+[.]?\d*$",str_re).group())
        result = str('{:.15f}'.format(x-y))
        return result
    elif re.search("^\-\d+[.]?\d*\-",s) != None:
        str_re = re.search("^\-\d+[.]?\d*\-\d+[.]?\d*", s).group()
        x = float(re.search("^\-\d+[.]?\d*", str_re).group())
        y = float(re.search("\d+[.]?\d*$", str_re).group())
        result = str('{:.15f}'.format(x-y))
        return result
    elif re.search('^\-\d+[.]?\d*$',s) != None:
        str_re = re.search('^\-\d+[.]?\d*$',s).group()
        return str_re
#乘法
def mutiply(s):
    if re.search("^[\-]?\d+[.]?\d*\*[\-]?\d+[.]?\d*",s) != None:
        str_re = re.search("[\-]?\d+[.]?\d*\*[\-]?\d+[.]?\d*", s).group()
        x = float(re.search("^[\-]?\d+[.]?\d*",str_re).group())
        y = float(re.search("[\-]?\d+[.]?\d*$",str_re).group())
        result = str('{:.15f}'.format(x*y)) # 设定小数位数限制
        return result
    else:
        err = 'Maybe anything is Error!'
        return err
#除法
def division(s):
    if re.search("^[\-]?\d+[.]?\d*\/[\-]?\d+[.]?\d*",s) != None:
        str_re = re.search("[\-]?\d+[.]?\d*\/[\-]?\d+[.]?\d*", s).group()
        x = float(re.search("^[\-]?\d+[.]?\d*",str_re).group())
        y = float(re.search("[\-]?\d+[.]?\d*$",str_re).group())
        result = str('{:.15f}'.format(x/y)) #设定小数位数限制
        return result
    else:
        err = 'Maybe anything is Error!'
        return err
#检查是否有中文,有中文返回True
def check_zh(s):
    check_zh = ('\u4e00' <= i <= '\u9fa5' for i in s)
    for zh in check_zh:
        if zh:
            return True
        else:
            continue
#检查输入的计算式是否有错误,此处做中间空格删除处理,有字母中文报错
def check_str(s):
    checkblank_list = re.findall('\s',s)
    checkword_list = re.findall('[A-Za-z]',s)
    if check_zh(s):
        err = "Error:计算式中出现中文!"
        print(err)
        return False
    if re.findall('[+\-*/(]$',s):
        print('计算式结尾不能为+ - * / ( ')
        return False
    if re.findall('[()]',s): #中文括号替换为英文的
        #print('Error:计算式中出现文括号!')
        s = re.sub('(','(',s)
        s = re.sub(')',')',s)
        #return False
    if checkblank_list and (not checkword_list):
        s_list=re.split(' ',s)
        #print (s_list)
        s = ''.join(s_list)
        s_list = list(s)
        i = s_list.count('(')
        k = s_list.count(')')
        if i == k: #检查括号前括号和后括号数量是否匹配
            return s
        else:
            print("The brackets Error,Pls Check!")
            return False
    elif (not checkword_list) and (not checkword_list):
        s_list = list(s)
        i = s_list.count('(')
        k = s_list.count(')')
        if i == k:#检查括号前括号和后括号数量是否匹配
            return s
        else:
            print("The brackets Error,Pls Check!")
            return False
    else:
        err = "ERR:\nThe inputting expression evaluation Error!Pls try again!"
        print(err)
#计算结果后的+- 和--情况替换
def format_str(s):
    while True:
        if re.findall('(\+\-)|(\-\-)',s):
            if re.findall('^\-\-',s):
                s = re.sub('^\-\-','',s)
            s = re.sub('\+\-','-',s)
            s = re.sub('\-\-', '+', s)
            continue
        else:
            break
    return s
#括号内计算
def bracket_rules(s):
    old_s = s
    while re.findall("\([^()]+\)",old_s):
        #print('计算式:',old_s)
        inner_bracket = re.search("\([^()]+\)",old_s).group()
        inner_bracket_str = re.search('[^()]+',inner_bracket).group()#去掉括号

        if re.findall('^[\-]?\d+[.]?\d*$',inner_bracket_str):
            old_s = old_s.replace(inner_bracket,inner_bracket_str)
            old_s = format_str(old_s)
            continue
        result_bracket = no_bracket_rules(inner_bracket_str)
        old_s = old_s.replace(inner_bracket,result_bracket)
    return old_s
#无括号时四则混合运算
def no_bracket_rules(s):
    result_str = s
    while not re.findall('^[\-]?\d+[.]?\d*$',result_str):
        #print("计算式:",result_str)
        if re.findall('(\*)|(\/)',result_str):
            f = re.search("(\*)|(\/)",result_str).group()
            if  f =="*":
            # if re.findall('\d+[.]?\d*\*[\-]?\d+[.]?\d*',result_str):
                exprssion = re.search('\d+[.]?\d*\*[\-]?\d+[.]?\d*',result_str).group()
                result = mutiply(exprssion) #乘法结果
                #print("%s 结果:%s" % (exprssion, result))
                result_str = result_str.replace(exprssion,result)
                result_str = format_str(result_str)
                continue
            elif f == '/':
            # elif re.findall('\d+[.]?\d*\/[\-]?\d+[.]?\d*',result_str):
                exprssion = re.search('\d+[.]?\d*\/[\-]?\d+[.]?\d*',result_str).group()
                result = division(exprssion)
                #print("%s 结果:%s" % (exprssion, result))
                result_str = result_str.replace(exprssion, result)
                result_str = format_str(result_str)
                continue
        elif re.findall('(\-)|(\+)',result_str):
            f2 = re.search("(\-)|(\+)",result_str).group()
            if f2 =='+':
            # if re.findall("(\d+[.]?\d*\+\d+[.]?\d*)|(^\-\d+[.]?\d*\+)",result_str):
                exprssion = re.search('(\d+[.]?\d*\+[\-]?\d+[.]?\d*)|(^[\-]?\d+[.]?\d*\+[\-]?\d+[.]?\d*)', result_str).group()
                result = plus(exprssion)
                #print("%s 结果:%s" % (exprssion, result))
                result_str = result_str.replace(exprssion, result)
                result_str = format_str(result_str)
                continue
            elif f2 == '-':
                if re.search('(\d+[.]?\d*\-[\-]?\d+[.]?\d*)|(^[\-]?\d+[.]?\d*\-[\-]?\d+[.]?\d*)',result_str):
            # elif re.findall("(\d+[.]?\d*\-\d+[.]?\d*)|(^\-\d+[.]?\d*\-\d+[.]?\d+)",result_str):
                    exprssion = re.search('(\d+[.]?\d*\-[\-]?\d+[.]?\d*)|(^[\-]?\d+[.]?\d*\-[\-]?\d+[.]?\d*)',result_str).group()
                    result = minus(exprssion)
                    #print("%s 结果:%s" % (exprssion, result))
                    result_str = result_str.replace(exprssion, result)
                    result_str = format_str(result_str)
                    continue
                elif re.search('^[\-]?\d+[.]?\d*\+[\-]?\d+[.]?\d*',result_str):
                    exprssion = re.search('^[\-]?\d+[.]?\d*\+[\-]?\d+[.]?\d*',result_str).group()
                    result = plus(exprssion)
                    #print("%s 结果:%s"%(exprssion,result))
                    result_str = result_str.replace(exprssion, result)
                    result_str = format_str(result_str)
                    continue

    return result_str
#计算
def calculator(expression):
    if re.findall('[()]',expression):
        result_bracket = bracket_rules(expression)
        result = no_bracket_rules(result_bracket)
        return  result
    elif re.findall('[^()]',expression):
        result = no_bracket_rules(expression)
        return result
#执行计算
def running_calculator():
    while True:
        expression = input("----------------\nPlease input + - * / ( ) to calculate\n[q exit]\033[1;36;43m>>:\033[0m ").strip()
        check_s = check_str(expression)
        if len(expression) == 0:continue
        elif expression == 'q':
            print("Exit Calculator...")
            break
        elif check_s:
            result = calculator(check_s)
            print("\033[1;36;43m❤The END Result:\033[0m", result)
        else:
            continue
#启动运行
running_calculator()

位数多了·· 出错~~~ @_@  计算过程中小数位数太多用e- 表示时会有问题···死循环 规避该问题 格式化小数位数   

result = str('{:.15f}'.format(x*y)) # 设定小数位数限制
result = str('{:.15f}'.format(x/y)) #设定小数位数限制

你可能感兴趣的:(python3)