python用正則對字符串進行運算


import re


def nul_div(source):
    """
    處理乘法和除法,先利用搜索出需要進行乘法和除法的表達式,然后利用正則將字符串分割,進行乘法和除法的運算
    :param source: 要進行計算的字符串
    :return: 將計算過的表達式替換到原有字符串,返回計算后的字符串
    """
    source = str_format(source)
    while re.search('\*|/', source):
        ret = re.search('[. 0-9]+?[\*/][+-]?[. 0-9]+', source).group()
        res_data = re.findall('(-?[\d\.]+|\*|/)', ret)
        if res_data[1] == '*':
            res = float(res_data[0]) * float(res_data[2])
        else:
            res = float(res_data[0]) / float(res_data[2])
        source = source.replace(ret, str(res))
    return source


def add_sub(source):
    """
    處理加法和減法,先利用搜索出需要進行加法和減法的表達式,然后利用正則將字符串分割,進行加法和減法的運算
    :param source: 要進行計算的字符串
    :return: 將計算過的表達式替換到原有字符串,返回計算后的字符串
    """
    source = str_format(source)
    while re.search('[\+-]?[.0-9]*[\+-]+[.0-9]*', source):
        ret = re.search('[\+-]?[.0-9]*[\+-]+[.0-9]*', source).group()
        res_data = re.findall(r'([\d\.]+|\+|-)', ret)
        if len(res_data) == 2:
            if res_data[0] == '-':
                res = -float(res_data[1])
            else:
                res = float(res_data[1])
            source = source.replace(ret, str(res))
            return source
        elif len(res_data) > 2:
            if res_data[0] == '-':
                if res_data[2] == '-':
                    res = - float(res_data[1]) - float(res_data[3])
                else:
                    res = - float(res_data[1]) + float(res_data[3])
            elif res_data[0] == '+':
                if res_data[2] == '-':
                    res = float(res_data[1]) - float(res_data[3])
                elif res_data[2] == '+':
                    res = float(res_data[1]) + float(res_data[3])
                else:
                    res = float(res_data[1])
            else:
                if res_data[1] == '-':
                    res = float(res_data[0]) - float(res_data[2])
                else:
                    res = float(res_data[0]) + float(res_data[2])
        else:
            res = float(res_data[0])
            source = source.replace(ret, str(res))
            return source
        source = source.replace(ret, str(res))
    return source


# def add_sub(source):
#     """
#     處理加法和減法,先利用搜索出需要進行加法和減法的表達式,然后利用正則將字符串分割,進行加法和減法的運算
#     :param source: 要進行計算的字符串
#     :return: 將計算過的表達式替換到原有字符串,返回計算后的字符串
#     """
#     source = str_format(source)
#     while re.search('[. 0-9]+?[\+-][. 0-9]+', source):
#         ret = re.search('[\+-]?[.0-9]+?[\+-][. 0-9]+', source).group()
#         print(ret)
#         res_data = re.findall(r'([\d\.]+|\+|-)', ret)
#         print(res_data)
#         if res_data[0] == '-':
#             if res_data[2] == '-':
#                 res = - float(res_data[1]) - float(res_data[3])
#             else:
#                 res = - float(res_data[1]) + float(res_data[3])
#         elif res_data[0] == '+':
#             if res_data[2] == '-':
#                 res = float(res_data[1]) - float(res_data[3])
#             else:
#                 res = float(res_data[1]) + float(res_data[3])
#         else:
#             if res_data[1] == '-':
#                 res = float(res_data[0]) - float(res_data[2])
#             else:
#                 res = float(res_data[0]) + float(res_data[2])
#         source = source.replace(ret, str(res))
#     return source


def check_expression(source):
    """
    檢查字符串是否可以進行正常計算,看括號是否相等,是否含有字母
    :param source: 要進行計算的字符串
    :return: 如果不能正常進行計算返回False,否則返回True
    """
    check_result = True
    if not source.count('(') == source.count(')'):
        print('表達式錯誤!請檢查表達式中"("")"是否相等')
        check_result = False
    if re.findall('[a-z]', source.lower()):
        print('表達式錯誤!請檢查表達式中是否含有字母')
        check_result = False
    return check_result


def str_format(source):
    """
    對字符串進行簡單的替換,替換空格和加減法的符號
    :param source: 要進行替換的字符串
    :return: 返回替換后的字符串
    """
    source = source.replace(' ', '')
    source = source.replace('++', '+')
    source = source.replace('+-', '-')
    source = source.replace('-+', '-')
    source = source.replace('--', '+')
    return source


def str_calculation(source):
    """
    計算字符串,先判斷是否可以計算,然后進行簡單的替換,判斷是否含有括號,進行計算
    :param source: 要進行計算的字符串
    :return: 返回計算結果
    """
    if check_expression(source):
        data = str_format(source)
        while re.search('\(', data):
            r_data = re.search('\([^()]+\)', data).group()
            data_r = nul_div(r_data)
            data_r = add_sub(data_r)
            data = str_format(data.replace(r_data, data_r[1:-1]))
        else:
            data_r = nul_div(data)
            data_r = add_sub(data_r)
            data = str_format(data.replace(data, data_r))
    return data

if __name__ == '__main__':
    s = "1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )"
    s1 = '1-2*((60-30-8.0*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'
    s2 = '--9'
    print(str_calculation(s))
    print(eval(s))
    print(str_calculation(s1))
    print(eval(s1))
    print(str_calculation(s2))
    print(eval(s2))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM