search
HomeBackend DevelopmentPython Tutorialpython正则表达式之作业计算器

作业:计算器开发

实现加减乘除及拓号优先级解析
用户输入 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )等类似公式后,必须自己解析里面的(),+,-,*,/符号和公式,运算后得出结果,结果必须与真实的计算器所得出的结果一致
一、说明:

有一点bug就是不能计算幂次方,如:'6**6'会报错

该计算器思路:
1、没用使用递归,先找出并计算所有括号里的公式,再计算乘除和加减
2、所有的数字都认为是浮点型操作,以此来保留小数
使用技术:
1、正则表达式
2、tkinter

二、流程图:

 

 三、代码如下:

#!/usr/bin/env python3
#antuor:Alan
 
import re
from functools import reduce
from tkinter import *
 
 
 
'''处理特殊-号运算'''
def minus_operation(expresstion):
  minus_operators = re.split("-",expresstion)
  calc_list = re.findall("[0-9]",expresstion)
  if minus_operators[0] =="":
    calc_list[0] = '-%s' % calc_list[0]
  res = reduce(lambda x,y:float(x)-float(y),calc_list)
  print(">>>>>>>>>>>>>>减号[%s]运算结果:" % expresstion,res)
  return res
 
'''reduce()对sequence连续使用function, 如果不给出initial, 则第一次调用传递sequence的两个元素,
以后把前一次调用的结果和sequence的下一个元素传递给function'''
 
 
 
 
'''处理双运算符号'''
def del_duplicates(expresstion):
  expresstion = expresstion.replace("++","+")
  expresstion = expresstion.replace("--","-")
  expresstion = expresstion.replace("+-","-")
  expresstion = expresstion.replace("--","+")
  expresstion = expresstion.replace('- -',"+")
  e
  return expresstion
 
'''*/运算函数'''
def mutiply_dividend(expresstion):
  calc_list = re.split("[*/]",expresstion)     #用* or /分割公式
  operators = re.findall("[*/]",expresstion)    #找出所有*和/号
  res = None
  for index,i in enumerate(calc_list):
    if res:
      if operators[index-1] =='*':
        res *= float(i)
      elif operators[index-1] =='/':
        res /=float(i)
    else :
      res = float(i)
  procession0 = "[%s]运算结果=" % expresstion,res
  final_result.insert(END,procession0)    #插入窗体
  print(procession0)
  return res
 
 
 
'''处理运算符号顺序混乱情况'''
def special_features(plus_and_minus_operators,multiply_and_dividend):
 
  for index,i in enumerate(multiply_and_dividend):
    i = i.strip()
    if i.endswith("*") or i.endswith("/"):
      multiply_and_dividend[index] = multiply_and_dividend[index] + plus_and_minus_operators[index] + multiply_and_dividend[index+1]
      del multiply_and_dividend[index+1]
      del plus_and_minus_operators[index]
  return plus_and_minus_operators,multiply_and_dividend
 
 
 
def minus_special(operator_list,calc_list):
  for index,i in enumerate(calc_list):
    if i =='':
      calc_list[index+1] = i + calc_list[index+1].strip()
 
 
 
'''运算除了()的公式+-*/'''
def figure_up(expresstion):
  expresstion = expresstion.strip("()")    #去掉外面括号
  expresstion = del_duplicates(expresstion)  #去掉重复+-号
  plus_and_minus_operators = re.findall("[+-]",expresstion)
  multiply_and_dividend = re.split("[+-]",expresstion)
  if len(multiply_and_dividend[0].strip()) ==0:
    multiply_and_dividend[1] = plus_and_minus_operators[0] + multiply_and_dividend[1]
    del multiply_and_dividend[0]
    del plus_and_minus_operators[0]
 
  plus_and_minus_operators,multiply_and_dividend = special_features(plus_and_minus_operators,multiply_and_dividend)
  for index,i in enumerate(multiply_and_dividend):
    if re.search("[*/]",i):
      sub_res = mutiply_dividend(i)
      multiply_and_dividend[index] = sub_res
 
  print(multiply_and_dividend,plus_and_minus_operators)  #计算
  final_res = None
  for index,item in enumerate(multiply_and_dividend):
    if final_res:
      if plus_and_minus_operators[index-1] == '+':
        final_res += float(item)
      elif plus_and_minus_operators[index-1] == '-':
        final_res -= float(item)
    else:
      final_res = float(item)
  procession = '[%s]计算结果:' % expresstion,final_res
  final_result.insert(END,procession)    #插入窗体
  print(procession)
  return final_res
 
"""主函数:运算逻辑:先计算拓号里的值,算出来后再算乘除,再算加减"""
def calculate():
  expresstion = expresstions.get()         #获取输入框值
  flage = True
  calculate_res = None               #初始化计算结果为None
  while flage:
    m = re.search("\([^()]*\)",expresstion)    #先找最里层的()
    # pattern = re.compile(r"\([^()]*\)")
    # m = pattern.match(expresstion)
    if m:
      sub_res = figure_up(m.group())      #运算()里的公式
      expresstion = expresstion.replace(m.group(),str(sub_res))  #运算完毕把结果替换掉公式
    else:
      print('---------------括号已经计算完毕--------------')
      procession1 = "最终计算结果:",figure_up(expresstion)
      final_result.insert(END,procession1)   #插入窗体
      print('\033[31m最终计算结果:',figure_up(expresstion))
 
      flage = False
 
 
if __name__=="__main__":
  # res = calculate("1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )")
  window = Tk()         ###创建窗体
  window.title('计算器')    ###命名窗体
  frame1 = Frame(window)    ###框架1
  frame1.pack()        ###放置
  frame2 = Frame(window)    ###框架2
  frame2.pack()        ###放置
  lable = Label(frame1,text = "请输入公式:")  ###文字标签
  lable.pack()
  expresstions = StringVar()  ###输入框属性,字符串
  entryname = Entry(frame1,textvariable = expresstions) ###文本输入框
  bt_get_expresstions = Button(frame1,text = "提交",command = calculate) ###按钮挂件
  bt_get_expresstions.pack()
  entryname.pack()
  lable.grid(row =1,column =1)  ###位置
  entryname.grid(row=1,column =2)
  bt_get_expresstions.grid(row =1,column =3)
  final_result = Text(frame2)  ###计算结果显示框
  final_result.tag_config("here", background="yellow", foreground="blue")
  final_result.pack()
  window.mainloop()       ###事件循环

以上就是本文的全部内容,希望对大家的学习有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
如何使用Python正则表达式进行Word文件处理如何使用Python正则表达式进行Word文件处理Jun 22, 2023 am 09:57 AM

Python正则表达式是一种强大的匹配工具,它可以帮助我们在Word文件处理中快速识别并替换文字、样式和格式。本文将介绍如何使用Python正则表达式进行Word文件处理。一、安装Python-docx库Python-docx是Python中处理Word文档的功能库,使用它可以快速读取、修改、创建和保存Word文档。在使用Python-docx之前,需要保证

如何使用Python正则表达式处理数字和金额如何使用Python正则表达式处理数字和金额Jun 23, 2023 am 08:21 AM

Python正则表达式是一种强大的工具,可帮助我们在文本数据中进行精细、高效的匹配和搜索。在数字和金额的处理中,正则表达式也极为有用,可以准确地找到并提取其中的数字和金额信息。本文将介绍如何使用Python正则表达式处理数字和金额,帮助读者更好地应对实际的数据处理任务。一、处理数字1.匹配整数和浮点数正则表达式中,要匹配整数和浮点数,可以使用d+进行匹配,其

如何使用Python正则表达式进行单词分割如何使用Python正则表达式进行单词分割Jun 23, 2023 am 10:37 AM

Python正则表达式是一种强大的工具,可用于处理文本数据。在自然语言处理中,单词分割是一个重要的任务,它可以将一段文本分成单个单词。在Python中,我们可以使用正则表达式来完成单词分割的任务。下面将以Python3为例,介绍如何使用正则表达式进行单词分割。导入re模块re模块是Python内置的正则表达式模块,首先需要导入该模块。importre定义文

如何使用Python正则表达式进行容器编排如何使用Python正则表达式进行容器编排Jun 22, 2023 am 09:16 AM

在容器编排中,我们常常需要对一些信息进行筛选、匹配和替换等操作。Python提供了正则表达式这一强大的工具,可以帮助我们完成这些操作。本文将介绍如何使用Python正则表达式进行容器编排,包括正则基础知识、Pythonre模块的使用方法以及一些常见的正则表达式应用。一、正则表达式基础知识正则表达式(RegularExpression)是指一种文本模式,用

如何使用Python正则表达式进行内容提取如何使用Python正则表达式进行内容提取Jun 22, 2023 pm 03:04 PM

Python是一种广泛使用的高级编程语言,拥有丰富的库和工具,使得内容提取变得更加简单和高效。其中,正则表达式是一种非常重要的工具,Python提供了re模块来使用正则表达式进行内容提取。本文将为您介绍如何使用Python正则表达式进行内容提取的具体步骤。一、了解正则表达式的基本语法在使用Python正则表达式进行内容提取之前,首先需要了解正则表达式的基本语

如何使用Python正则表达式进行数据结构和算法如何使用Python正则表达式进行数据结构和算法Jun 22, 2023 pm 08:01 PM

Python正则表达式是一种基于模式匹配的字符串处理工具,它可以帮助我们快速有效地从文本中提取所需信息。在数据结构和算法中,正则表达式可以用来实现文本匹配、替换、分割等功能,为我们的编程提供更加强大的支持。本文将介绍如何使用Python正则表达式进行数据结构和算法。一、正则表达式的基础知识在开始之前,先了解一下正则表达式的一些基础知识:字符集:用方括号表示,

如何使用Python正则表达式进行代码审美和用户体验如何使用Python正则表达式进行代码审美和用户体验Jun 22, 2023 am 08:45 AM

在软件开发中,代码审美和用户体验常常被忽视,这导致许多软件在实际使用中出现问题。Python作为一门强大的编程语言,提供了正则表达式这一强大的工具来帮助我们解决这些问题。本文将介绍如何使用Python正则表达式进行代码审美和用户体验。一、Python正则表达式简介正则表达式是一种描述文本模式的语言,可以用来匹配、查找、替换和拆分文本。Python的re模块提

如何使用Python正则表达式进行代码重构如何使用Python正则表达式进行代码重构Jun 23, 2023 am 09:44 AM

在日常编码中,我们经常需要对代码进行修改和重构,以增加代码的可读性和可维护性。其中一个重要的工具就是正则表达式。本篇文章将介绍如何使用Python正则表达式进行代码重构的一些常用技巧。一、查找和替换正则表达式最常用的功能之一是查找和替换。假设我们需要将代码中所有的print语句替换成logging语句。我们可以使用以下正则表达式进行查找:prints*((.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),