zoukankan      html  css  js  c++  java
  • python学习----------re模块之计算器

    import re
    
    def form_s(s):
        s = s.replace('++','+')
        s = s.replace('+-','-')
        s = s.replace('-+','-')
        s = s.replace('--','+')
        return s
    
    def mul_sub(s):
        mul_regular = '[-]?d+.?d*[*/][-]?d+.?d*'
        n1 = re.search(mul_regular,s)
        print(n1.group())
        while re.search(mul_regular,s):
            n2=re.search(mul_regular,s).group()
    
            if n2.count('*') == 1:
                x,y = n2.split('*')
                result = str(float(x)*float(y))
                s = s.replace(n2,result)
                s=form_s(s)
            if n2.count('/') ==1:
                x,y =n2.split('/')
                #print(x,y)
                result = float(x)/float(y)
                result = str(result)
                s=s.replace(n2,result)
                s=form_s(s)
        return s
    
    def add_sub(s):
        add_regular = '-?d+.?d*[-+]d+.?d*'
        #n1 = re.search(add_regular,s)
        #print(n1.group())
        while re.search(add_regular,s):
            n2 = re.search(add_regular,s).group()
            if n2.count('+') == 1:
                x,y =n2.split('+')
                result =str(float(x)+float(y))
                s = s.replace(n2,result)
                s = form_s(s)
            if n2.count('-') == 1:
                x,y = n2.split('-')
                result = str(float(x)-float(y))
                s = s.replace((n2,result))
                s = form_s(s)
        return s
    
    if __name__ == '__main__':
        while 1:
            s=input("请输入计算式(退出按q):")
            if s == 'q':
                exit()
            else:
                print('计算式为',s)
                print('eval result = ',eval(s))
                print('规范式子为:',form_s(s))
                #m1 = re.search('([^()]+)',s)
                #print(m1)
                while re.search('([^()]+)',s):
                    m2 = re.search('([^()]+)',s).group()
                    re_str = mul_sub(m2)
                    #print(re_str)
                    re_str = add_sub(re_str)
                    #print(re_str)
                    s = form_s(s.replace(m2,re_str[1:-1]))
                    print(s)
    
                re_str = mul_sub(s)
                re_str = add_sub(re_str)
                #print(re_str)
                #s= form_s(s.replace(s,re_str[1:-1]))
                print('结果是:',re_str)
  • 相关阅读:
    解决PLSQL Developer中文横着显示的问题
    品优购_day06
    品优购_day05
    品优购_day04
    品优购_day03
    品优购_day02
    java 学习中遇到的问题(二)泛型中<? extends T>和<? super T>的区别
    java 学习中遇到的问题(一)方法调用中的值传递和引用传递
    java中的字符串比较
    自学java 第十一章持有对象
  • 原文地址:https://www.cnblogs.com/yujin123456/p/9690430.html
Copyright © 2011-2022 走看看