代码感觉有点绕,刚开始学习python,相关知识点还没全部学习到,还请各位大神多多指教
import re # 定义乘法 def mul(string): mul1 = re.search(‘-?\d+(?:\.\d+)?\*-?\d+(?:\.\d+)?‘, string) str1 = mul1.group() li = re.split(‘\*‘, str1) mul_ret = float(li[0]) * float(li[1]) if mul_ret < 0: return string.replace(string[mul1.start(): mul1.end()], str(mul_ret)) else: return string.replace(string[mul1.start(): mul1.end()], ‘+‘ + str(mul_ret)) # 定义除法 def div(string): div1 = re.search(‘-?\d+(?:\.\d+)?/-?\d+(?:\.\d+)?‘, string) str1 = div1.group() li = re.split(‘/‘, str1) div_ret = float(li[0]) / float(li[1]) if div_ret < 0: return string.replace(string[div1.start(): div1.end()], str(div_ret)) else: return string.replace(string[div1.start(): div1.end()], ‘+‘ + str(div_ret)) # 定义加法 def add(string): add1 = re.search(‘-?\d+(?:\.\d+)?\+-?\d+(?:\.\d+)?‘, string) str1 = add1.group() li = re.split(‘\+‘, str1) add_ret = float(li[0]) + float(li[1]) return string.replace(string[add1.start(): add1.end()], str(add_ret)) # 定义减法 def sub(string): sub1 = re.search(‘-?\d+(?:\.\d+)?--?\d+(?:\.\d+)?‘, string) str1 = sub1.group() if str1[0] == ‘-‘: str1 = str1[1:] li = re.split(‘-‘, str1, 1) sub_ret = 0 - float(li[0]) - float(li[1]) return string.replace(string[sub1.start(): sub1.end()], str(sub_ret)) else: li = re.split(‘-‘, str1, 1) sub_ret = float(li[0]) - float(li[1]) return string.replace(string[sub1.start(): sub1.end()], str(sub_ret)) # 去除括号 def brackets(string): string = re.sub(r‘ ‘, ‘‘, string) n = string.count(‘(‘) while n: n -= 1 m1 = re.search(‘(?<=\()[^\(\)]*(?=\))‘, string) str1 = m1.group() str1_ret = cal(str1) string = string.replace(string[m1.start() - 1: m1.end() + 1], str(str1_ret)) return string # 定义不含括号的运算 def cal(string): li = re.findall(‘\*|/‘, string) for i in li: if i == ‘*‘: string = mul(string) elif i == ‘/‘: string = div(string) n = 2 while n: string = string.replace(‘+-‘, ‘-‘) string = string.replace(‘--‘, ‘+‘) string = string.replace(‘-+‘, ‘-‘) string = string.replace(‘++‘, ‘+‘) n -= 1 if string[0] == ‘-‘ or ‘+‘: string = ‘0‘ + string li = re.findall(‘\+|-‘, string) for i in li: if i == ‘+‘: string = add(string) elif i == ‘-‘: string = sub(string) return string def jm_cal(string): cal_ret = cal(brackets(string)) return cal_ret
输入:
s = ‘-45 + 15 * (12 - 68 / (11 - 5 * 2 + (-9 )/ 4)* 6) / 4 + 6 - (14 / 9 + 8 * (-7) - 6 * 2 + 13) * 12‘
print(jm_cal(s))
输出:
1871.3333333333333
与直接调用eval()内置函数计算结果一致
利用正则表达式模拟计算器进行字符串的计算实现eval()内置函数功能
原文:https://www.cnblogs.com/xuminzgl/p/11998928.html