编程语言
首页 > 编程语言> > Python用正则实现计算字符串算式

Python用正则实现计算字符串算式

作者:互联网

Python用正则实现计算字符串算式

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import re

# 乘除法
def mul_div(s):
    if '*' in s:
        s = s.split('*')
        return float(s[0]) * float(s[1])
    elif '/' in s:
        s = s.split('/')
        return float(s[0]) / float(s[1])

# 加减法
def add_sub(s):
    if '+' in s:
        s = s.split('+')
        return float(s[0]) + float(s[1])
    else:
        if s[0] == '-':
            s = s[1::].split('-', 1)
            s[0] = '-' + s[0]
            return float(s[0]) - float(s[1])
        else:
            s = s.split('-', 1)
            return float(s[0]) - float(s[1])


# 替换字符串
def str_replace(lst1,lst2):
    for i in range(len(lst1)):
        global str1
        str1 = str1.replace(lst1[i], lst2[i])


# 匹配最内层括号
pattern1 = re.compile(r'\([^(^)]*?\)')
str1 = '1+2*(6/2-9+3*(3*9-9))'
str1 = '( )'.replace(' ',str1)
while True:
    if '(' not in str1 and ')' not in str1:
        break
    ret1 = pattern1.findall(str1)

    # 匹配括号内的内容
    ret2 = []
    pattern2 = re.compile(r'\((?P<tag>.*?)\)')
    for i in range(len(ret1)):
        ret = pattern2.search(ret1[i])
        ret2.append(ret.group('tag'))


        # 计算乘除法
        while True:
            pattern3 = re.compile(r'[-+*/]?(?P<tag>-?\d+(\.\d+)?[*/]-?\d+(\.\d+)?)')
            ret3 = pattern3.search(ret2[i])
            try:
                ret4 = ret3.group('tag')
            except Exception as e:
                pass
            if '*' not in ret2[i] and '/' not in ret2[i]:
                break
            else:
                ret2[i] = ret2[i].replace(ret4, str(mul_div(ret4)))
        # 计算加法
        while True:
            pattern3 = re.compile(r'-?\d+(\.\d+)?[-+]-?\d+(\.\d+)?')
            ret3 = pattern3.search(ret2[i])
            try:
                ret4 = ret3.group()
            except Exception as e:
                pass
            if '+' not in ret2[i] and '-' not in ret2[i][1::]:
                break
            else:
                ret2[i] = ret2[i].replace(ret4, str(add_sub(ret4)))


    str_replace(ret1,ret2)

print(str1)
#97.0

标签:ret2,算式,str1,float,Python,正则,括号,ret4
来源: https://www.cnblogs.com/nanke33/p/12101435.html