Day5:模块
一、模块
1、模块定义:用来从逻辑上组织python代码(可以定义变量、函数、类、逻辑),本质就是.py结尾的python文件(文件名:test.py,对应的模块名:test),实现一个功能
包的定义:用来从逻辑上组织模块,本质就是一个目录,必须带有一个__init__.py文件
2、导入模块方法
import module_name
import module1_name,module2_name
from module_name import * #导入此模块下所有内容,不建议使用
from module_name import m1,m2,m3
from module_name import say as module_say
(1)新建一个名module_test的Python Package,里面新建一个名为module.py文件,内容如下:
# Author:licy name="licy" def say(): print('hello licyss')
(2)再在module_test文件夹下新建一个test.py文件,内容如下:
# Author:licy import test print(test.name) test.say()
3、import本质(路径搜索和搜索路径)
导入模块的本质就是把python文件解释一遍
导入包的本质就是去执行这个包下面的__init__.py文件
4、导入优化
多个函数使用模块中的内容,就不要用import 模块名了,因为每次使用还得模块名.方法名,这样每次调用都得去引入这个模块,那么更快的效率就是用from module_name import m1,意思就是实现将代码拿过来了,就不用每次取import了
5、模块的分类
(1)标准库(sys、os)
a、time与datetime
strftime("格式",struct_time)#格式化的字符串
strptime("格式化字符串","格式")#struct_time
# Author:licy import time,datetime print(time.time())#获取时间戳 #time.sleep(1)#睡几秒 #print(time.gmtime())#返回UTC标准时间 #print(time.localtime())#返回本国家时间 x=time.localtime() print(x.tm_yday)#取出当前年 print(time.mktime(x))#将元组格式转换成时间戳 print(time.strftime("%Y-%m-%d %H:%M:%S",x))#将元组格式进行格式化输出 print(time.strptime("2017-07-27 08:58:55","%Y-%m-%d %H:%M:%S"))#将格式化后的内容转换为元组格式 print(datetime.datetime.now())#获取当前时间 print(datetime.datetime.now()+datetime.timedelta(3))#3天后的时间 print(datetime.datetime.now()+datetime.timedelta(hours=3))#3个小时后的时间 #修改当前时间 c_time=datetime.datetime.now() print(c_time.replace(minute=3,hour=2))
b、random模块
# Author:licy import random print(random.random())#随机0-1之间的浮点数 print(random.randint(1,3))#随机[1,3]之间的整数 print(random.randrange(1,3))#随机[1,3)之间的整数 print(random.choice('hello'))#参数可以是字符串、列表、元组 print(random.sample('hello',2))#从前面序列取两位出来 print(random.uniform(1,3))#返回指定区间的浮点数 #洗牌功能 list=[1,2,3,4,5,6] random.shuffle(list) print(list)
# Author:licy #生成随机验证码 import random checkcode='' for i in range(4): current=random.randrange(0,4) #字母 if current==i: tmp=chr(random.randint(65,90)) else: #数字 tmp=random.randint(0,9) checkcode+=str(tmp) print(checkcode)
c、os模块
# Author:licy import os print(os.getcwd())#获取当前的操作目录 os.chdir("C:\\Users")#切换当前目录 os.chdir(r"C:\Users")#切换当前目录 print(os.curdir)#返回当前目录 print(os.pardir)#返回上一级目录 print(os.makedirs(r'C:\a\b\c\d'))#递归创建目录 os.removedirs(r'C:\a\b\c\d')#删除空目录 os.mkdir(r'C:\a')#只能一个个创建 os.rmdir(r'C:\a')#只能一个个删除 print(os.listdir('D:')) print(os.stat(os.curdir))#获取文件、目录信息 print(os.sep)#获取当前操作系统的路径分隔符 print(os.linesep)#获取当前操作系统的行终止符 print(os.environ)#获取当前操作系统的环境变量 print(os.pathsep)#获取当前操作系统环境变量的分隔符 print(os.path.abspath(__file__))#返回path规范化的绝对路径 print(os.path.split(r'C:\a\b.txt'))#不考虑路径是否存在 print(os.path.exists(r'C:\a'))#判断一个路径是否存在
d、sys模块
e、shutil模块
f、json&pickle模块
json:用户字符串和python数据类型进行转换(序列化)
pickle:用于python特有的类型和python的数据类型进行转换
g、xml处理模块
f、re正则表达式模块
'.' 默认匹配除\n之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行 '^' 匹配字符开头,若指定flags MULTILINE,这种也可以匹配上(r"^a","\nabc\neee",flags=re.MULTILINE) '$' 匹配字符结尾,或e.search("foo$","bfoo\nsdfsf",flags=re.MULTILINE).group()也可以 '*' 匹配*号前的字符0次或多次,re.findall("ab*","cabb3abcbbac") 结果为['abb', 'ab', 'a'] '+' 匹配前一个字符1次或多次,re.findall("ab+","ab+cd+abb+bba") 结果['ab', 'abb'] '?' 匹配前一个字符1次或0次 '{m}' 匹配前一个字符m次 '{n,m}' 匹配前一个字符n到m次,re.findall("ab{1,3}","abb abc abbcbbb") 结果'abb', 'ab', 'abb'] '|' 匹配|左或|右的字符,re.search("abc|ABC","ABCBabcCD").group() 结果'ABC' '(...)' 分组匹配,re.search("(abc){2}a(123|456)c", "abcabca456c").group() 结果 abcabca456c '\A' 只从字符开头匹配,re.search("\Aabc","alexabc") 是匹配不到的 '\Z' 匹配字符结尾,同$ '\d' 匹配数字0-9 '\D' 匹配非数字 '\w' 匹配[A-Za-z0-9] '\W' 匹配非[A-Za-z0-9] 's' 匹配空白字符、\t、\n、\r , re.search("\s+","ab\tc1\n3").group() 结果 '\t' '(?P<name>...)' 分组匹配 re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})","371481199306143242").groupdict("city") 结果{'province': '3714', 'city': '81', 'birthday': '1993'}
# Author:licy import re print(re.match('^licy','licy1232133isagood').group())#匹配licy print(re.match('^licy\d+','licy1232133isagood').group())#匹配licy1232133 print(re.match('^.+','licy1232133isagood').group())#匹配licy1232133
(2)开源模块(第三方模块)
(3)自定义模块