惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

阮一峰的网络日志
阮一峰的网络日志
Apple Machine Learning Research
Apple Machine Learning Research
量子位
D
DataBreaches.Net
云风的 BLOG
云风的 BLOG
博客园 - 聂微东
博客园_首页
D
Docker
博客园 - 叶小钗
S
SegmentFault 最新的问题
大猫的无限游戏
大猫的无限游戏
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
J
Java Code Geeks
H
Hackread – Cybersecurity News, Data Breaches, AI and More
A
About on SuperTechFans
博客园 - 三生石上(FineUI控件)
F
Fortinet All Blogs
小众软件
小众软件
aimingoo的专栏
aimingoo的专栏
爱范儿
爱范儿
腾讯CDC
罗磊的独立博客
雷峰网
雷峰网
博客园 - Franky

博客园 - Chen.HJ

Nginx安装和遇到过的坑 Redis安装与常用命令 Nginx、Tomcat和Redis配置文件说明 python + selenium 获取标签文本的为空解决办法 Python读取Excel Python使用paramiko的SFTP get或put整个目录 Linux系统性能监控工具nmon python+selenium个人学习笔记11-登录封装与调用 python+selenium+unittest测试框架4-邮件发送最新测试报告 python+selenium+unittest测试框架3-项目构建和发送邮件 python+selenium+unittest测试框架2-装饰器@classmethod python+selenium+unittest测试框架1-unittest单元测试框架和断言 python+selenium个人学习笔记10-调用JavaScript和截图 python+selenium个人学习笔记9-文件上传和cookie操作 python+selenium个人学习笔记8-获取信息和勾选框 python+selenium个人学习笔记7-警告框处理和下拉框选择 python+selenium个人学习笔记6-元素等待 python+selenium个人学习笔记5-多窗口和多表单切换 python+selenium个人学习笔记4-鼠标和键盘操作
python用正则对字符串进行运算
Chen.HJ · 2019-10-12 · via 博客园 - Chen.HJ
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))