# Python 70行代码实现简单算式计算器解析

result = re.search('\([^()]+\)',s)

```
import re
'''根据本逻辑，‘-'必须早于‘+'循环 否则特殊情况会报错
原因是若出现符号--，会被处理为+，若+优先遍历，最后+将无法被处理'''
oper_char = ['^','*','/','-','+']
def format_str(s):
'''除去空格和两边括号'''
return s.replace(' ','').replace('(','').replace(')','')

def handle_symbol(s):
'''处理多个运算符并列的情况'''
return s.replace('+-','-').replace('--','+').replace('-+','-').replace('++','+')

def cal(x,y,opertor):
'''加减乘除开方'''
if opertor == '^':return x**y
elif opertor == '*':return x*y
elif opertor == '/':return x/y
elif opertor == '+':return x+y
elif opertor == '-':return x-y

def Bottom_operation(s):
'''无括号运算 返回一个浮点数
symbol用于判断返回值是正还是负'''
symbol = 0
s = handle_symbol(s)
for c in oper_char:
while c in s:
id,char = (s.find(c),c)
if c in ('*','/') and '*' in s and '/' in s:
ids,idd = (s.find('*'),s.find('/'))
id,char = (ids,'*') if ids <= idd else (idd,'/')
if c in ('+','-') and '+' in s and '-' in s:
ida,idd = (s.find('+'),s.find('-'))
id,char = (ida,'+') if ida <= idd else (idd,'-')
if id == -1:break
left,right = ('','')
for i in range(id - 1,-1,-1):
if s[i] in oper_char:break
left = s[i] + left
for i in range(id + 1,len(s)):
if s[id+1] == '-':
right += s[i]
continue
if s[i] in oper_char:break
right += s[i]
if right == '' or left == '':
if s[0] in ('-','+'):
if '+' not in s[1:] and '-' not in s[1:]:break
s = s[1:].replace('-','负').replace('+','-').replace('负','+')
symbol += 1
continue
else:return '输入算式有误'
old_str = left + char + right
new_str = str(cal(float(left),float(right),char))
s = handle_symbol(s.replace(old_str,new_str))
return float(s) if symbol % 2 == 0 else -float(s)

def get_bottom(s):
'''获取优先级最高的表达式'''
res = re.search('\([^()]+\)',s)
if res != None:return res.group()

if __name__ == '__main__':
while True:
s1 = input('请输入您要计算的表达式(支持加减乘除开方): ')
while get_bottom(s1) != None:
source = get_bottom(s1)
result = Bottom_operation(format_str((source)))
s1 = s1.replace(source,str(result))
print(Bottom_operation(format_str(s1)))
```

QQ号联系： 360901061

【本文对您有帮助就好】