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

推荐订阅源

Blog — PlanetScale
Blog — PlanetScale
Webroot Blog
Webroot Blog
T
Troy Hunt's Blog
S
Secure Thoughts
S
Security @ Cisco Blogs
S
Security Affairs
Forbes - Security
Forbes - Security
W
WeLiveSecurity
H
Hacker News: Front Page
T
Threatpost
Google Online Security Blog
Google Online Security Blog
S
Schneier on Security
有赞技术团队
有赞技术团队
WordPress大学
WordPress大学
www.infosecurity-magazine.com
www.infosecurity-magazine.com
博客园 - Franky
腾讯CDC
IT之家
IT之家
博客园 - 聂微东
L
LINUX DO - 最新话题
罗磊的独立博客
Hacker News - Newest:
Hacker News - Newest: "LLM"
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 三生石上(FineUI控件)
Hacker News: Ask HN
Hacker News: Ask HN
C
CXSECURITY Database RSS Feed - CXSecurity.com
C
Cybersecurity and Infrastructure Security Agency CISA
C
CERT Recently Published Vulnerability Notes
Know Your Adversary
Know Your Adversary
V
Vulnerabilities – Threatpost
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
博客园_首页
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Cisco Talos Blog
Cisco Talos Blog
S
SegmentFault 最新的问题
酷 壳 – CoolShell
酷 壳 – CoolShell
Hugging Face - Blog
Hugging Face - Blog
L
LINUX DO - 热门话题
美团技术团队
G
GRAHAM CLULEY
T
The Exploit Database - CXSecurity.com
AI
AI
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Jina AI
Jina AI
Help Net Security
Help Net Security
N
News | PayPal Newsroom
月光博客
月光博客
Spread Privacy
Spread Privacy
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
N
News and Events Feed by Topic

博客园 - 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))