python函数和常用模块(三),Day5
- 递归
- 反射
- os模块
- sys模块
- hashlib加密模块
- 正则表达式
反射
python中的反射功能是由以下四个内置函数提供:hasattr、getattr、setattr、delattr,改四个函数分别用于对对象内部执行:检查是否含有某成员、获取成员、设置成员、删除成员。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | class Foo( object ): def __init__( self ): self .name = 'wupeiqi' def func( self ): return 'func' obj = Foo() # #### 检查是否含有成员 #### hasattr (obj, 'name' ) hasattr (obj, 'func' ) # #### 获取成员 #### getattr (obj, 'name' ) getattr (obj, 'func' ) # #### 设置成员 #### setattr (obj, 'age' , 18 ) setattr (obj, 'show' , lambda num: num + 1 ) # #### 删除成员 #### delattr (obj, 'name' ) delattr (obj, 'func' ) |
os模块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | os.getcwd() # 获取当前工作目录,即当前python脚本工作的目录路径 os.chdir( "dirname" ) # 改变当前脚本工作目录;相当于shell下cd os.curdir # 返回当前目录: ('.') os.pardir # 获取当前目录的父目录字符串名:('..') os.makedirs( 'dir1/dir2' ) # 可生成多层递归目录 os.removedirs( 'dirname1' ) # 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推 os.mkdir( 'dirname' ) # 生成单级目录;相当于shell中mkdir dirname os.rmdir( 'dirname' ) # 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname os.listdir( 'dirname' ) # 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印 os.remove() # 删除一个文件 os.rename( "oldname" , "new" ) # 重命名文件/目录 os.stat( 'path/filename' ) # 获取文件/目录信息 os.sep # 操作系统特定的路径分隔符,win下为"\\",Linux下为"/" os.linesep # 当前平台使用的行终止符,win下为"\t\n",Linux下为"\n" os.pathsep # 用于分割文件路径的字符串 os.name # 字符串指示当前使用平台。win->'nt'; Linux->'posix' os.system( "bash command" ) # 运行shell命令,直接显示 os.environ # 获取系统环境变量 os.path.abspath(path) # 返回path规范化的绝对路径 os.path.split(path) # 将path分割成目录和文件名二元组返回 os.path.dirname(path) # 返回path的目录。其实就是os.path.split(path)的第一个元素 os.path.basename(path) # 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素 os.path.exists(path) # 如果path存在,返回True;如果path不存在,返回False os.path.isabs(path) # 如果path是绝对路径,返回True os.path.isfile(path) # 如果path是一个存在的文件,返回True。否则返回False os.path.isdir(path) # 如果path是一个存在的目录,则返回True。否则返回False os.path.join(path1[, path2[, ...]]) # 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略 os.path.getatime(path) # 返回path所指向的文件或者目录的最后存取时间 os.path.getmtime(path) # 返回path所指向的文件或者目录的最后修改时间 |
sys模块
1 2 3 4 5 6 7 8 9 | sys.argv # 命令行参数List,第一个元素是程序本身路径 sys.exit(n) # 退出程序,正常退出时exit(0) sys.version # 获取Python程序的版本信息 sys.maxint # 最大的Int值 sys.path # 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值 sys.platform # 返回操作系统平台的名称 sys.stdin # 输入相关 sys.stdout # 输出相关 sys.stderror # 错误相关 |
hashlib加密模块
用于加密相关的操作,代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import hashlib # ######## md5 ######## hash = hashlib.md5() hash .update( 'admin' ) print hash .hexdigest() # ######## sha1 ######## hash = hashlib.sha1() hash .update( 'admin' ) print hash .hexdigest() # ######## sha256 ######## hash = hashlib.sha256() hash .update( 'admin' ) print hash .hexdigest() # ######## sha384 ######## hash = hashlib.sha384() hash .update( 'admin' ) print hash .hexdigest() # ######## sha512 ######## hash = hashlib.sha512() hash .update( 'admin' ) print hash .hexdigest() |
以上加密算法虽然依然非常厉害,但时候存在缺陷,即:通过撞库可以反解。所以,有必要对加密算法中添加自定义key再来做加密。
1 2 3 4 5 6 7 | import hashlib # ######## md5 ######## hash = hashlib.md5( '898oaFs09f' ) hash .update( 'admin' ) print hash .hexdigest() |
还不够吊?python 还有一个 hmac 模块,它内部对我们创建 key 和 内容 再进行处理然后再加密
1 2 3 4 | import hmac h = hmac.new( 'wueiqi' ) h.update( 'hellowo' ) print h.hexdigest() |
不能再牛逼了!!!
1 2 3 4 5 6 7 8 9 10 11 12 13 | import hashlib obj = hashlib.md5() obj.update(bytes( 'admin' , encoding = 'utf-8' )) result = obj.hexdigest() print (result) # 加key密钥 obj = hashlib.md5(bytes( 'xxxxxxxx' , encoding = 'utf-8' )) obj.update(bytes( 'admin' , encoding = 'utf-8' )) result = obj.hexdigest() print (result) |
正则表达式
re模块用于对python的正则表达式的操作。
字符:
. 匹配除换行符以外的任意字符
\w 匹配字母或数字或下划线或汉字
\s 匹配任意的空白符
\d 匹配数字
\b 匹配单词的开始或结束
^ 匹配字符串的开始
$ 匹配字符串的结束
次数:
* 重复零次或更多次
+ 重复一次或更多次
? 重复零次或一次
{n} 重复n次
{n,} 重复n次或更多次
{n,m} 重复n到m次
IP: ^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$ 手机号: ^1[3|4|5|8][0-9]\d{8}$
1、match(pattern, string, flags=0)
从起始位置开始根据模型去字符串中匹配指定内容,匹配单个
- 正则表达式
- 要匹配的字符串
- 标志位,用于控制正则表达式的匹配方式
import re obj = re.match('\d+', '123uuasf') if obj: print obj.group()
2、search(pattern, string, flags=0)
根据模型去字符串中匹配指定内容,匹配单个
import re obj = re.search('\d+', 'u123uu888asf') if obj: print obj.group()
3、group和groups
a = "123abc456" print re.search("([0-9]*)([a-z]*)([0-9]*)", a).group() print re.search("([0-9]*)([a-z]*)([0-9]*)", a).group(0) print re.search("([0-9]*)([a-z]*)([0-9]*)", a).group(1) print re.search("([0-9]*)([a-z]*)([0-9]*)", a).group(2) print re.search("([0-9]*)([a-z]*)([0-9]*)", a).groups()
4、findall(pattern, string, flags=0)
上述两中方式均用于匹配单值,即:只能匹配字符串中的一个,如果想要匹配到字符串中所有符合条件的元素,则需要使用 findall。
import re obj = re.findall('\d+', 'fa123uu888asf') print obj
5、sub(pattern, repl, string, count=0, flags=0)
用于替换匹配的字符串
content = "123abc456" new_content = re.sub('\d+', 'sb', content) # new_content = re.sub('\d+', 'sb', content, 1) print new_content
相比于str.replace功能更加强大
6、split(pattern, string, maxsplit=0, flags=0)
根据指定匹配进行分组
content = "'1 - 2 * ((60-30+1*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2) )'" new_content = re.split('\*', content) # new_content = re.split('\*', content, 1) print new_content
content = "'1 - 2 * ((60-30+1*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2) )'" new_content = re.split('[\+\-\*\/]+', content) # new_content = re.split('\*', content, 1) print new_content
inpp = '1-2*((60-30 +(-40-5)*(9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2))' inpp = re.sub('\s*','',inpp) new_content = re.split('\(([\+\-\*\/]?\d+[\+\-\*\/]?\d+){1}\)', inpp, 1) print new_content
相比于str.split更加强大

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步