python3 运用正则实现计算器

import re

bracket = re.compile(r‘\([^()]+\)‘) # 寻找最内层括号规则
mul = re.compile(r‘(\d+\.?\d*\*-\d+\.?\d*)|(\d+\.?\d*\*\d+\.?\d*)‘)  # 寻找乘法运算规则
div = re.compile(r‘(\d+\.?\d*/-\d+\.?\d*)|(\d+\.?\d*/\d+\.?\d*)‘)  # 寻找除法运算规则
add = re.compile(r‘(-?\d+\.?\d*\+-\d+\.?\d*)|(-?\d+\.?\d*\+\d+\.?\d*)‘)  # 寻找加法运算规则
sub = re.compile(r‘(-?\d+\.?\d*--\d+\.?\d*)|(-?\d+\.?\d*-\d+\.?\d*)‘)  # 寻找减法运算规则
c_f = re.compile(r‘\([^*/]\)‘)  # 检查括号内是否运算完毕规则
strip = re.compile(r‘[^(].*[^)]‘)  # 脱括号规则
n_md = re.compile(‘\([^*/]+\)‘)
res = re.compile(‘([+-]?\d+\.?\d*)‘)
ills= re.compile(r‘[^0-9*/+\-\(\)]‘)
def Mul(exp):
    result = re.split(r‘\*‘,mul.search(exp).group())
    return exp.replace(mul.search(exp).group(),str(float(result[0])*float(result[1])))

def Div(exp):
    result = re.split(r‘/‘, div.search(exp).group())
    return exp.replace(div.search(exp).group(), str(float(result[0])/ float(result[1])))

def Add_Sub(exp):
    exp = exp.replace(‘++‘,‘+‘)
    exp = exp.replace(‘+-‘,‘-‘)
    exp = exp.replace(‘--‘,‘+‘)
    exp = exp.replace(‘-+‘,‘-‘)
    # print(exp)
    nums = re.findall(‘[+\-]?\d+\.?\d*‘,exp)
    count = 0
    for num in nums:
        count += float(num)
    return str(count)

# 没有添加用户输入判断
def calculator():
    while True:
        exp = input(‘>>>‘)
        if exp.strip().upper() == ‘Q‘:
            print(‘退出程序‘)
            exit()
        else:
            exp = exp.replace(‘ ‘,‘‘)
            if ills.search(exp):
                print(‘有非法字符!‘)
            else:
                while bracket.search(exp):
                    result = bracket.search(exp).group()
                    print(result)
                    if div.search(result):
                        exp = exp.replace(result,Div(result))
                    elif mul.search(result):
                        exp = exp.replace(result,Mul(result))
                    elif n_md.search(result):
                        exp = exp.replace(n_md.search(result).group(),Add_Sub(result))
                        print(exp)

                while True:
                    if div.search(exp):
                        result = div.search(exp).group()
                        exp = exp.replace(result,Div(result))
                    elif mul.search(exp):
                        result = mul.search(exp).group()
                        exp = exp.replace(result,Mul(result))
                    else:
                        result = Add_Sub(exp)
                        print(‘The answer is: %.2f‘%float(result))
                        break
calculator()
# print(1-2*((60-30+(-40/-5+20/4+3*4*5/2)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))-99*2)
# print(69*(69+1)*100+2*8)

原文地址:https://www.cnblogs.com/kuraki/p/9797248.html

时间: 2024-08-03 20:59:30

python3 运用正则实现计算器的相关文章

Python3中正则模块re.compile、re.match及re.search

本文实例讲述了Python3中正则模块re.compile.re.match及re.search函数用法.分享给大家供大家参考,具体如下: re模块 re.compile.re.match. re.search re 模块官方说明文档 正则匹配的时候,第一个字符是 r,表示 raw string 原生字符,意在声明字符串中间的特殊字符不用转义. 比如表示 '\n',可以写 r'\n',或者不适用原生字符 '\n'. 推荐使用 re.match re.compile() 函数 编译正则表达式模式,

Python3中正则模块re.compile、re.match及re.search函数用法详解

Python3中正则模块re.compile.re.match及re.search函数用法 re模块 re.compile.re.match. re.search 正则匹配的时候,第一个字符是 r,表示 raw string 原生字符,意在声明字符串中间的特殊字符不用转义. 比如表示 ‘\n',可以写 r'\n',或者不适用原生字符 ‘\n'. 推荐使用 re.match re.compile() 函数 编译正则表达式模式,返回一个对象.可以把常用的正则表达式编译成正则表达式对象,方便后续调用及

Python 正则实现计算器

1 1 # !/usr/bin/env/ python3 2 2 # -*- coding: utf-8 -*- 3 3 4 4 """用户输入计算表达式,显示计算结果""" 5 5 6 6 __author__ = 'Jack' 7 7 8 8 import re 9 9 10 10 bracket = re.compile(r'\([^()]+\)') # 寻找最内层括号规则 11 11 mul = re.compile(r'(\d+\.?\

【Python3之正则re】

一.正则re 1.正则表达式定义 正则就是用一些具有特殊含义的符号组合到一起(称为正则表达式)来描述字符或者字符串的方法.或者说:正则就是用来描述一类事物的规则.(在Python中)它内嵌在Python中,并通过 re 模块实现.正则表达式模式被编译成一系列的字节码,然后由用 C 编写的匹配引擎执行. 2.常用的正则表达式 3.贪婪模式与非贪婪模式 正则表达式通常用于在文本中查找匹配的字符串.Python里数量词默认是贪婪的(在少数语言里也可能是默认非贪婪),总是尝试匹配尽可能多的字符:非贪婪的

python3 re正则模块

一.常用的正则表达式: 1.".":默认匹配除\n之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行 2."^":匹配字符开头,若指定flag MULTILINE,这种也可以匹配上(r"^a","\nabc\neee",flags=re.MULTILINE) 3."$":匹配字符结尾,或re.search("foo$","bfoo\nsdfsf"

Python3中正则的贪婪匹配模式

什么是贪婪模式 正则在进行匹配时,从开始位置查找最远的结束位置,这种模式称之为贪婪模式. 在进行HTML标签类似内容获取时,贪婪模式会导致整个内容的返回,需要使用非贪婪模式. 固定的书写规则 : .*? 这种方式就是非贪婪模式,或者说是惰性模式 Python中默认使用贪婪模式 例子 >>> import re >>> str = '<div>---hello---</div><div>---world---</div>'

正则与计算器

import re def repeat_func(s): #去掉重复的+--号 repeat = re.findall('\+\-|\-\-|\++\-\+', s) if len(repeat) > 0: for i in repeat: if i == '--' or i == '++': s = s.replace(i, '+') if i == '+-' or s == '-+': s = s.replace(i, '-') return s def mul_devid(content

正则表达示 for Python3

前情提要 从大量的文字内容中找到自己想要的东西,正则似乎是最好的方法.也是写爬虫不可缺少的技能.所以,别墨迹了赶紧好好学吧! 教程来自http://www.runoob.com/python3/python3-reg-expressions.html,感谢菜鸟教程. 一. 在Python3中 正则为 re 模块 import re 二.re.match函数 re.match –>从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话match()就返回none,语法: re.match(p

Python基础(递归、模块、包以及正则)-day05

写在前面 上课第四天,打卡: 如果再见不能红着眼,是否还能红着脸: 一.协程函数(生成器:yield的表达式形式) 1.yield 的语句形式: yield 1 2.yield 的表达式形式: x=yield 注意:next(g) #等同于 g.send(None),示例如下: 1 def deco(func): 2 def wrapper(*args,**kwargs): 3 res=func(*args,**kwargs) 4 next(res) 5 return res 6 return