Python正規表示式實現簡單四則運算解析器

2021-08-18 04:41:35 字數 3174 閱讀 6201

實現目標:

1. 正確處理加減乘除及括號優先順序

2. 保證結果無誤,可用eval()測試

3.練習正規表示式使用

#coding utf-8

""" 用正規表示式實現四則運算表示式解析器

思路:根據計算優先順序,先計算內部括號裡面的運算,並用計算結果的字串形式替換原表示式,直到沒有括號運算子;

然後匹配乘法和除法的運算因子,按從左往右的順序依次更新計算結果,最後處理加減法運算。

tips: 需要特別注意對輸入的檢測和修正(如多餘空格、非法輸入)和浮點數的匹配

"""import re

import functools

defcheckinput

(formula):

"""檢測輸入合法與否,是否包含字母等非法字元"""

return

not re.search("[^0-9+\-*/.()\s]",formula)

defformatinput

(formula):

"""標準化輸入表示式,去除多餘空格等"""

formula = formula.replace(' ','')

formula = formula.replace('++', '+')

formula = formula.replace('+-', '-')

formula = formula.replace('-+', '-')

formula = formula.replace('--', '+')

return formula

defmul_divoperation

(s):

"""乘法除法運算"""

# 1-2*-14969036.7968254

s = formatinput(s)

sub_str = re.search('(\d+\.?\d*[*/]-?\d+\.?\d*)', s)

while sub_str:

sub_str = sub_str.group()

if sub_str.count('*'):

l_num, r_num = sub_str.split('*')

s = s.replace(sub_str, str(float(l_num)*float(r_num)))

else:

l_num, r_num = sub_str.split('/')

s = s.replace(sub_str, str(float(l_num) / float(r_num)))

#print(s)

s = formatinput(s)

sub_str = re.search('(\d+\.?\d*[*/]\d+\.?\d*)', s)

return s

defadd_minusoperation

(s):

"""加法減法運算

思路:在最前面加上+號,然後正則匹配累加

"""s = formatinput(s)

s = '+' + s

#print(s)

tmp = re.findall('[+\-]\d+\.?\d*', s)

s = str(functools.reduce(lambda x, y:float(x)+float(y), tmp))

#print(tmp)

return s

defcompute

(formula):

"""無括號表示式解析"""

#ret = formula[1:-1]

ret = formatinput(formula)

ret = mul_divoperation(ret)

ret = add_minusoperation(ret)

return ret

defcalc

(formula):

"""計算程式入口"""

has_parenthesise = formula.count('(')

if checkinput(formula):

formula = formatinput(formula)

while has_parenthesise:

sub_parenthesise = re.search('\([^()]*\)', formula) #匹配最內層括號

if sub_parenthesise:

#print(formula+"...before")

formula = formula.replace(sub_parenthesise.group(), compute(sub_parenthesise.group()[1:-1]))

#print(formula+'...after')

else:

print('沒有括號了...')

has_parenthesise = false

ret = compute(formula)

print('結果為:')

return ret

else:

print("輸入有誤!")

if __name__ == '__main__':

#print(mul_divoperation('17.0*7/3.0*3+1/2'))

#print(add_minusoperation('1-2-3+1-4'))

#print(calc('(9+8)*7/(5-2)*3+1/2'))

s = "99+(1+2=(8)-(7+9))"

print(eval('1.5 - 2.4 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'))

print(calc('1.5 - 2.4 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'))

print( calc("1 - 2 * ( (60-30 +(-9-2-5-2*3-5/3-40*4/2-3/5+6*3) * (-9-2-5-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )"))

Python 正規表示式 簡單示例

最近使用python正規表示式處理資料較多,先將python使用正規表示式匹配文字的示例程式整理一下。從檔案中讀取內容,使用正規表示式匹配import re import sys 主函式 重定向輸出位置 output sys.stdout outputfile open test.txt w sys...

python正規表示式簡單使用

python實用re模組來操作正規表示式,常用的方法如下 看下面一段 import re content abacadae matcher re.match ab content 字串開頭是ab,匹配成功 print matcher.span matcher re.match ac content ...

Python 正規表示式簡單了解

search 用字串裡的每乙個元素 去匹配找的元素 1 匹配單個字元 d 數字 d 非數字 匹配任意字元 除了 n 匹配裡的任意乙個字元 s 匹配空格 s 匹配非空格 w 匹配字母數字 下劃線 w 匹配特殊符號 2 匹配多個字元 匹配前乙個字元出現0次或著無限次 匹配前乙個字元出現1次或著無限次 至...