这世界上根本就不存在真正的感同身受

python 23day--python模块的应用

一、random模块的应用:

生成五为数字与字母组合的验证码:

 1 import random
 2 def v_code():#生成随机验证码
 3     ret = ''
 4     for i in range(5):
 5         num = random.randint(0,9)
 6         num1 = str(num)
 7         ref = chr(random.randint(65,122))
 8         ret += random.choice([num1,ref])
 9     print(ret)
10 v_code()

二、re模块的应用

10个重要的re 的元字符:

^    以什么开头

$   以什么结尾

.    匹配任意字符(\除外)

*   匹配0到任意次

?  匹配0次或者1次(非贪婪模式)

+  匹配1到任意次

{}  {m,n}至少重复m次,最多重复n次

[]  [a-z]匹配a到z的字符

()  分组

\  转义

I  或的关系

计算器:

 1 # 编辑者:闫龙
 2 import re #导入re模块(正则表达式)
 3 calc2 = "1-2*((60-30+(-40/52)*(9-2*5/3+7/3*-99/4*2998+10*568/14))-(-4*3)/(16-3*2))"
 4 calc1 = "1-2*((60-30+(-40/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))"
 5 calc = "1-2*((60*30+(-40/5)*(9*2*5/3+7/3*99/4*2998+10*568/14))-(-4*32)/(16-3*2))"
 6 def Format(Str):
 7     "格式化运算式"
 8     Str = Str.replace("+-","-")
 9     Str = Str.replace("-+", "-")
10     Str = Str.replace("++", "+")
11     Str = Str.replace("--", "+")
12     return Str
13 def SumCut(Str):
14     while re.search("-?[0-9]+\.?[0-9]*[-+][0-9]+\.?[0-9]*",Str):
15         newRes= re.search("-?[0-9]+\.?[0-9]*[-+][0-9]+\.?[0-9]*",Str)
16         WhatIs = newRes.group()
17         if(WhatIs.find("-") > 0):
18             l = WhatIs.split("-")
19             Str = Str.replace(WhatIs,str(float(l[0])-float(l[1])))
20         elif(WhatIs.find("+") > 0):
21             l = WhatIs.split("+")
22             Str = Str.replace(WhatIs,str(float(l[0])+float(l[1])))
23     return Str.replace("(","").replace(")","")
24 def MulDiv(Str):
25     while re.search("-?[0-9]+\.?[0-9]*[/*].?[0-9]+\.?[0-9]*",Str):
26         newRes= re.search("-?[0-9]+\.?[0-9]*[/*].?[0-9]+\.?[0-9]*",Str)
27         WhatIs = newRes.group()
28         if(WhatIs.find("/") > 0):
29             l = WhatIs.split("/")
30             Str = Str.replace(WhatIs,str(float(l[0])/float(l[1])))
31         elif(WhatIs.find("*") > 0):
32             l = WhatIs.split("*")
33             if(float(l[0])<0 and float(l[1])<0):
34                 Str = Str.replace(WhatIs, "+"+str(float(l[0]) * float(l[1])))
35             else:
36                 Str = Str.replace(WhatIs,str(float(l[0])*float(l[1])))
37     return Format(Str)
38 while re.search("\([^()]+\)",calc):
39     res = re.search("\([^()]+\)", calc)
40     resTwo = MulDiv(Format(res.group()))
41     resTwo = SumCut(resTwo)
42     calc = calc.replace(res.group(),resTwo)
43 else:
44     resTwo = MulDiv(calc)
45     resTwo = SumCut(resTwo)
46     calc = resTwo
47 print(calc)

 

posted @ 2018-12-26 16:11  默言0419  阅读(187)  评论(0编辑  收藏  举报