正则与计算器

import re

def repeat_func(s):
    #去掉重复的+——号
    repeat = re.findall('\+\-|\-\-|\++\-\+', s)
    if len(repeat) > 0:
        for i in repeat:
            if i == '--' or i == '++':
                s = s.replace(i, '+')
            if i == '+-' or s == '-+':
                s = s.replace(i, '-')
    return s

def mul_devid(content):
    # 计算乘除
    pattern1 = '-?\d+\.?\d*(?:\*|\/)-?\d+\.?\d*'
    while 1:
        first = re.search(pattern1, content)
        #匹配乘除
        if first:
            if '*' in first.group():
                new1 = first.group().split('*')
                new = float(new1[0]) * float(new1[1])
                new = str(new)
            else:
                new1 = first.group().split('/')
                new = float(new1[0]) / float(new1[1])
                new = str(new)

            res=re.search(r'-\d+\.?\d*(?:\*|\/)-\d+\.?\d*',content)
            #如果两个负数相乘或相除,添加正号
            if res :
                new='+' + new
            content = repeat_func(content)
            content = content.replace(first.group(), new)

        else:
            break
    return content

def add_minus(content):
    # 计算加减
    pattern2 = '-?\d+\.?\d*(?:\+|\-)\d+\.?\d*'
    while 1:
        first = re.search(pattern2, content)
        if first:
            #根据不同的模式分别计算
            choice1 = re.search('(-\d+\.?\d*-\d+\.?\d*)', first.group())
            if choice1:
                new1 = first.group().split('-')
                new = -(float(new1[1]) + float(new1[2]))

            choice2 = re.search('(-\d+\.?\d*\+\d+\.?\d*)|(\d+\.?\d*\+\d+\.?\d*)', first.group())
            if choice2:
                new1 = first.group().split('+')
                new = float(new1[1]) + float(new1[0])

            choice3 =  re.search('\d+\.?\d*-\d+\.?\d*', first.group())
            if choice3:
                new1 = first.group().split('-')
                new = float(new1[0]) - float(new1[1])
            #
            # content=repeat_func(content)
            content = content.replace(first.group(), str(new))

        else:
            break

    return content

def calculate(content):
    content = mul_devid(content)
    content = add_minus(content)
    return content

def bracket(s):
    while 1:
        first = re.search(r'\([^()]+\)', s)
        if first:
            new=calculate(first.group())
            s=s.replace(first.group(),new[1:-1])
            s=repeat_func(s)
        else: break
    end=calculate(s)
    return end

s='1-2*((60-30+(-40/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'

print(eval(s))
print(bracket(s))

 

posted @ 2017-06-29 20:10  皖心  阅读(155)  评论(0编辑  收藏  举报