python四则运算表达式_通过Python正则表达式实现简单四则运算

python练习作业...import math, re

string = "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) )"

string = ''.join(string.split()) #字符串去空格

#字符串格式化

def stringFormat(string):

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

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

string = string.replace('*+-', '*-')

string = string.replace('/+-', '/-')

return string

#不含括号字符串公式计算函数

def stringCalculate(string):

fResult = 0.0  # 浮点型计算结果

tmpListAdd = list()  # 加减法列表

#公式数据拆分

strList = stringFormat(string).split('+')

#第一步先根据加法将字符串分段,如果分段内含有乘除法,则进入乘除法分段计算,否则转化成浮点数,存入列表

for inLoopAdd in strList:  #第一层循环---加减法分割

#乘法模块

if'*' in inLoopAdd or '/' in inLoopAdd:

tmpListMulti = list()  #乘法列表

for inloopMulti in inLoopAdd.split('*'):   #第二层----乘法分割

#除法模块

if '/' in inloopMulti:

divList = inloopMulti.split('/')

fDivResult = float(divList[0])

for inloopDiv in range(len(divList)-1):  #第三层-----内层除法计算

fDivResult /= float(divList[inloopDiv+1])

tmpListMulti.append(fDivResult)

else:

tmpListMulti.append(float(inloopMulti))

fMultiResult = 1

for inloop in tmpListMulti:

fMultiResult *= inloop

tmpListAdd.append(fMultiResult)

elif inLoopAdd:

tmpListAdd.append(float(inLoopAdd))

#将各分段结果累加

for fAddResult in tmpListAdd:

fResult += fAddResult

return str(fResult)

#去括号

while('(' in string):

temString = re.search('\([0-9+\-*./]*\)', string).group()

string = string.replace(temString, stringCalculate(temString[1:-1]))

print(stringCalculate(string))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python 爬虫中,正则表达式是非常常用的技术,可以帮助我们从网页中提取出需要的信息。下面是一些常用的正则表达式符号和方法: 1. ".":匹配任意单个字符,除了换行符。 2. "^":匹配字符串的开始位置。 3. "$":匹配字符串的结束位置。 4. "*":匹配前一个字符出现 0 次或多次。 5. "+":匹配前一个字符出现 1 次或多次。 6. "?":匹配前一个字符出现 0 次或 1 次。 7. "{m}":匹配前一个字符出现 m 次。 8. "{m,n}":匹配前一个字符出现 m 到 n 次。 9. "(...)":分组匹配,匹配括号内的表达式。 10. "[...]":匹配括号内的任意一个字符。 11. "[^...]":匹配不在括号内的任意一个字符。 12. "\d":匹配数字,等同于 [0-9]。 13. "\D":匹配非数字,等同于 [^0-9]。 14. "\s":匹配空白字符,包括空格、制表符、换行符等。 15. "\S":匹配非空白字符。 16. "\w":匹配单词字符,包括字母、数字、下划线。 17. "\W":匹配非单词字符。 在 Python 中,使用 re 模块进行正则表达式的匹配。常用的方法包括: 1. re.compile(pattern):将正则表达式编译成一个对象,提高匹配效率。 2. re.search(pattern, string):在字符串中搜索匹配正则表达式的第一个位置。 3. re.findall(pattern, string):在字符串中搜索匹配正则表达式的所有位置,并返回一个列表。 4. re.sub(pattern, repl, string):将字符串中所有匹配正则表达式的字符替换为指定的字符串。 以上是一些常用的正则表达式符号和方法,希望能对你有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值