Python-Regex實現計算機功能,python-Regex

來源:互聯網
上載者:User

Python-Regex實現計算機功能,python-Regex

需求:

使用者輸入運算運算式,終端顯示計算結果

代碼:

 1 # !/usr/bin/env/ python3 2 # -*- coding: utf-8 -*- 3  4 """使用者輸入計算運算式,顯示計算結果""" 5  6 __author__ = 'Jack' 7  8 import re 9 10 bracket = re.compile(r'\([^()]+\)')  # 尋找最內層括弧規則11 mul = re.compile(r'(\d+\.?\d*\*-\d+\.?\d*)|(\d+\.?\d*\*\d+\.?\d*)')  # 尋找乘法運算規則12 div = re.compile(r'(\d+\.?\d*/-\d+\.?\d*)|(\d+\.?\d*/\d+\.?\d*)')  # 尋找除法運算規則13 add = re.compile(r'(-?\d+\.?\d*\+-\d+\.?\d*)|(-?\d+\.?\d*\+\d+\.?\d*)')  # 尋找加法運算規則14 sub = re.compile(r'(\d+\.?\d*--\d+\.?\d*)|(\d+\.?\d*-\d+\.?\d*)')  # 尋找減法運算規則15 c_f = re.compile(r'\(?\+?-?\d+\)?')  # 檢查括弧內是否運算完畢規則16 strip = re.compile(r'[^(].*[^)]')  # 脫括弧規則17 18 19 def Mul(s):20     """計算運算式中的乘法運算"""21     exp = re.split(r'\*', mul.search(s).group())22     return s.replace(mul.search(s).group(), str(float(exp[0]) * float(exp[1])))23 24 25 def Div(s):26     """計算運算式中的除法運算"""27     exp = re.split(r'/', div.search(s).group())28     return s.replace(div.search(s).group(), str(float(exp[0]) / float(exp[1])))29 30 31 def Add(s):32     """計算運算式中的加法運算"""33     exp = re.split(r'\+', add.search(s).group())34     return s.replace(add.search(s).group(), str(float(exp[0]) + float(exp[1])))35 36 37 def Sub(s):38     """計算運算式中的減法運算"""39     exp = re.split(r'-', sub.search(s).group())40     return s.replace(sub.search(s).group(), str(float(exp[0]) - float(exp[1])))41 42 43 def calc():44     while True:45         s = input('Please input the expression(q for quit):')  # 例:'1+2- (3*  4-3/2+ (   3-2*(3+  5 -3*  -0.2-3.3*2.2 -8.5/ 2.4 )+10) +10)'46         if s == 'q':47             break48         else:49             s = ''.join([x for x in re.split('\s+', s)])  # 將運算式按空格分割並重組50             if not s.startswith('('):  # 若使用者輸入的運算式首尾無括弧,則統一格式化為:(運算式)51                 s = str('(%s)' % s)52             while bracket.search(s):  # 若運算式s存在括弧53                 s = s.replace('--', '+')  # 檢查運算式,並將--運算替換為+運算54                 s_search = bracket.search(s).group()  # 將最內層括弧及其內容賦給變數s_search55                 if div.search(s_search):  # 若除法運算存在(必須放在乘法之前)56                     s = s.replace(s_search, Div(s_search))  # 執行除法運算並將結果替換原運算式57                 elif mul.search(s_search):  # 若乘法運算存在58                     s = s.replace(s_search, Mul(s_search))  # 執行乘法運算並將結果替換原運算式59                 elif sub.search(s_search):  # 若減法運算存在(必須放在加法之前)60                     s = s.replace(s_search, Sub(s_search))  # 執行減法運算並將結果替換原運算式61                 elif add.search(s_search):  # 若加法運算存在62                     s = s.replace(s_search, Add(s_search))  # 執行加法運算並將結果替換原運算式63                 elif c_f.search(s_search):  # 若括弧內無任何運算(類似(-2.32)除外)64                     s = s.replace(s_search, strip.search(s_search).group())  # 將括弧脫掉,例:(-2.32)---> -2.3265 66             print('The answer is: %.2f' % (float(s)))67 68 if __name__ == '__main__':69     calc()
Regex實現計算機功能

運行效果:

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.