python模块——re模块(简单的计算器功能实现_eval版)

Posted Cong0ks

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python模块——re模块(简单的计算器功能实现_eval版)相关的知识,希望对你有一定的参考价值。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = "loki"

# Usage: Make a Diy Calculator
# example:
#    ‘1 - 2 * ((60-30 +(-40/5) * (9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))‘

import re
RE_RULE = ([^()]+)


def arithmetical(temp):
    result = eval(temp)
    return result


def main(arithmetic):
    step = 0
    while 1:
        step += 1
        result = re.search(RE_RULE, arithmetic)
        if result:  # if exist ‘()‘
            temp_ = result.group()
            calc_res = str(arithmetical(temp_))
            arithmetic = re.sub(RE_RULE, calc_res, arithmetic)  # replace  source values
            print(arithmetic, "step: %s" % step)
        else:  # if not ‘()‘
            return arithmetical(arithmetic)


if __name__ == __main__:
print("result: %s" % (main(user_input)))

 


以上是关于python模块——re模块(简单的计算器功能实现_eval版)的主要内容,如果未能解决你的问题,请参考以下文章

Python 3.x--使用re模块,实现计算器运算实例

python re模块实现计算器

走入计算机的第二十五天(内置模块3之正则表达式)

python 简单实现正则表达式和python中的re模块。

Python之re模块实现正则表达式

Python之re模块实现正则表达式