python中常用的模块一
一,常用的模块
模块就是我们将装有特定功能的代码进行归类,从代码编写的单位来看我们的程序,从小到大的顺序:
一条代码<语句块,<代码块(函数,类)<模块我们所写的所有py文件都是模块
引入模块的方式
1,import 模块
2,from xxx import 模块
二,collections模块
collections 模块主要封装了一些关于集合类的相关操作,比如我们学过的iterable,iterator等等.除了这些以外,collections
还提供了一些除了基本数据类型以外的数据集合类型,Counter,deque,OrderDict,defaultdict以及namedtuple
1,counter是一个计数器,主要用来计数
计算一个字符串中每个字符出现的次数:
# import collections from collections import Counter 方法一 s = "I am sylar, I have a dream, freedom...." dic = {} for el in s: dic[el] = dic.setdefault(el, 0) + 1 print(dic) 方法二 qq = Counter(s) print("__iter__" in dir(qq)) for item in qq: print(item, qq[item]) #显示 #{'I': 2, ' ': 7, 'a': 5, 'm': 3, 's': 1, 'y': 1, 'l': 1, 'r': 3, ',': 2, 'h': 1, 'v': 1, 'e': 4, 'd': 2, 'f': 1, 'o': 1, '.': 4} 计算列表中"五花马"出现的次数 lst = ["五花马", "千金裘", "不会", "不会", "不会"] c = Counter(lst) print(c['五花马']) 打印字典中两个key dic = {"a":"b", "c":"d"} print(dic.keys())
2 deque 双向队列
两种数据结构:1栈,2,队列
1,栈:FILO.先进后出 2对列:FILO.先进先出
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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | 例子栈 from collections import Counter class Stack: def __init__( self , size): self .index = 0 # 栈顶指针 self .lst = [] self .size = size # 给栈添加元素 def push( self , item): if self .index = = self .size: # 栈已经满了. 不能再装东西了 raise StackFullError( 'the stack is full' ) self .lst.insert( self .index, item) # 对于空列表. 需要insert插入内容 # self.lst[self.index] = item # 把元素放到栈里 self .index + = 1 # 栈顶指针向上移动 # 从栈中获取数据 def pop( self ): if self .index = = 0 : raise StackEmptyError( "the stack is empty" ) self .index - = 1 # 指针向下移动 item = self .lst.pop( self .index) # 获取元素. 删除. return item s = Stack( 5 ) s.push( "馒头1号" ) s.push( "馒头2号" ) s.push( "馒头3号" ) s.push( "馒头4号" ) s.push( "馒头5号" ) print (s.pop()) print (s.pop()) print (s.pop()) print (s.pop()) print (s.pop()) # # lst = [] lst.append( "哈哈1" ) lst.append( "哈哈2" ) lst.append( "哈哈3" ) lst.append( "哈哈4" ) print (lst.pop()) print (lst.pop()) print (lst.pop()) print (lst.pop()) |
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 | 队列例子一 import queue # q = queue.Queue() # 创建队列 q.put( "李嘉诚" ) q.put( "陈冠希" ) q.put( "周润发" ) q.put( "吴彦祖" ) print (q.get()) print (q.get()) print (q.get()) print (q.get()) # print(q.get()) # 队列中如果没有元素了. 继续获取的话. 会阻塞 print ( "拿完了" ) 例子二 from collections import deque q = deque() # 创建一个双向队列 q.append( "高圆圆" ) q.append( "江疏影" ) q.appendleft( "赵又廷" ) q.appendleft( "刘大哥" ) # 刘大哥 赵又廷 高圆圆 江疏影 print (q.pop()) # 从右边获取数据 print (q.pop()) print (q.popleft()) # 从左边获取数据 print (q.popleft()) print (q.pop()) |
3 namedtuple命名元组
1 2 3 4 5 6 7 8 | 命名元组,给元组内的元素进行命名, from collections import namedtuple # ⾃⼰定义了⼀个元组, 如果灵性够好, 这其实就是创建了⼀个类 nt = namedtuple( "point" , [ "x" , "y" ]) p = nt( 1 , 2 ) print (p) print (p.x) print (p.y) |
4 orderdict和defaultdict
orderdict 顾名思义. 字典的key默认是⽆序的. ⽽OrderedDict是有序的
1 2 3 4 5 6 7 8 9 10 | dic = { 'a' : '娃哈哈' , 'b' : '薯条' , 'c' : '胡辣汤' } print (dic) from collections import OrderedDict od = OrderedDict({ 'a' : '娃哈哈' , 'b' : '薯条' , 'c' : '胡辣汤' }) print (od) defaultdict: 可以给字典设置默认值. 当key不存在时. 直接获取默认值: from collections import defaultdict dd = defaultdict( list ) # 默认值list print (dd[ '娃哈哈' ]) # [] 当key不存在的时候. 会自动执行构造方法中传递的内容. |
defaultdict
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | d = defaultdict( list ) # {} # 参数位置给的内容必须是可调用的 d[ "周杰伦" ] = "昆凌" print (d[ "周杰伦" ]) # 从字典中获取数据的时候. 如果这个key不存在. 去执行可执行的内容, 拿到的是一个空列表 例二 lst = [ 11 , 22 , 33 , 44 , 55 , 66 , 77 , 88 , 99 ] d = defaultdict( list ) for el in lst: if el < 66 : d[ "key1" ].append(el) # key1默认是不存在的. 但是可以拿key1. 一个空列表. else : d[ "key2" ].append(el) print (d) 例三 def func(): return "胡辣汤" d = defaultdict(func) print (d[ "哈哈" ]) print (d) |
三. 时间模块
时间模块应用于如何计算时间差如何按照客户的要求展示时间
例如
1 2 | import time print (time.time()) # 1538927647.483177 系统时间 |
系统时间是上面的一连串的数字,需要对时间进行格式化,那样就引出了另一种时间格式
在python中时间有三种表现形式
1. 时间戳(timestamp). 时间戳使⽤的是从1970年01月01日 00点00分00秒到现在
一共经过了多少秒... 使用float来表示
1 2 3 | 获取当前系统时间, 时间戳 print (time.time()) # 1542166230.6139991, 给机器看的, 以1970-01-01 00:00:00 数据库存储的是这个时间 格式化时间 2018 - 11 - 14 11 : 22 : 56 2018 / 11 / 14 11 : 22 : 56 |
2. 格式化时间(strftime). 这个时间可以根据我们的需要对时间进行任意的格式化.
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 | import time s = time.strftime( "%Y-%m-%d %H:%M:%S" ) # 必须记住 print (s) 日期格式化的标准: % y 两位数的年份表示( 00 - 99 ) % Y 四位数的年份表示( 000 - 9999 ) % m ⽉份( 01 - 12 ) % d ⽉内中的⼀天( 0 - 31 ) % H 24 小时制小时数( 0 - 23 ) % I 12 进时制小时数( 01 - 12 ) % M 分钟数( 00 = 59 ) % S 秒( 00 - 59 ) % a 本地简化星期名称 % A 本地完整星期名称 % b 本地简化的月份名称 % B 本地完整的月份名称 % c 本地相应的日期表示和时间表示 % j 年内的一天( 001 - 366 ) % p 本地A.M.或P.M.的等价符 % U 一年中的星期数( 00 - 53 )星期天为星期的开始 % w 星期( 0 - 6 ),星期天为星期的开始 % W 一年中的星期数( 00 - 53 )星期⼀为星期的开始 % x 本地相应的日期表示 % X 本地相应的时间表示 % Z 当前时区的名称 % % % 号本身 |
3. 结构化时间(struct_time). 这个时间主要可以把时间进⾏分类划分. 比如. 1970
年01月01日 00点00分00秒
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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | # 从时间戳 -> 格式化时间 t = time.localtime( 1542513992 ) # 时区 gmtime() 格林尼治时间. print (t) str_time = time.strftime( "%Y-%m-%d %H:%M:%S" , t) print (str_time) #格式化时间 -> 时间戳 #2018-11-18 12:06:32 s = "2018-11-18 12:06:32" t = time.strptime(s, "%Y-%m-%d %H:%M:%S" ) # string parse time print (t) # # 结构化时间 -> 时间戳 ss = time.mktime(t) print (ss) print (time.strftime( "%Y年%m月%d日" )) # 中文 import locale locale.setlocale(locale.LC_CTYPE, "chinese" ) # 用时间戳计算出时间差(秒) begin_struct_time = time.strptime(begin, "%Y-%m-%d %H:%M:%S" ) end_stract_time = time.strptime(end, "%Y-%m-%d %H:%M:%S" ) begin_second = time.mktime(begin_struct_time) end_second = time.mktime(end_stract_time) # 秒级的时间差 180000 diff_time_sec = abs (begin_second - end_second) # 转换成分钟 diff_min = int (diff_time_sec / / 60 ) print (diff_min) diff_hour = diff_min / / 60 # 1 diff_min_1 = diff_min % 60 # 30 print ( "时间差是 %s小时%s分钟" % (diff_hour, diff_min_1)) 经典案例 # 用时间戳计算出时间差(秒) begin_struct_time = time.strptime(begin, "%Y-%m-%d %H:%M:%S" ) end_stract_time = time.strptime(end, "%Y-%m-%d %H:%M:%S" ) begin_second = time.mktime(begin_struct_time) end_second = time.mktime(end_stract_time) # 秒级的时间差 180000 diff_time_sec = abs (begin_second - end_second) # 转化成结构化时间 t = time.gmtime(diff_time_sec) # 最好用格林尼治时间。 否则有时差 print (t) print ( "时间差是%s年%s月 %s天 %s小时%s分钟" % (t.tm_year - 1970 , t.tm_mon - 1 , t.tm_mday - 1 ,t.tm_hour, t.tm_min )) |
四随机数模块random
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import random print (random.randint( 1 , 2 )) # [start, end] print (random.random()) # (0,1)之间的小数 print (random.uniform( 3 , 10 )) # (3, 10 )的随机小数 n = random.randrange( 1 , 10 , 3 ) # [1, 10) 从奇数中获取到随机数 while n ! = 10 : n = random.randrange( 1 , 10 , 3 ) for i in range ( 1 , 10 , 3 ): #拿出1到10中每三个取一个的值 print (i) print (random.choice([ 1 , '周杰伦' , [ "盖伦" , "胡辣汤" ]])) ## 1或者23或者[4,5]) print (random.sample([ 1 , '23' , [ 4 , 5 ]], 2 )) # 列表元素任意2个组合 lst = [ "周杰伦" , "昆凌" , "马化腾" , "马丽" , "沈腾" , "秋雅" ] random.shuffle(lst) print (lst) lst = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ] random.shuffle(lst) # 随机打乱顺序 print (lst) |
五.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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | 所有和操作系统相关的内容都在os模块 os.makedirs( 'dirname1/dirname2' ) 可⽣成多层递归⽬录 os.removedirs( 'dirname1' ) 若⽬录为空,则删除,并递归到上⼀级⽬录,如若也为空,则删 除,依此类推 os.mkdir( 'dirname' ) ⽣成单级⽬录;相当于shell中mkdir dirname os.rmdir( 'dirname' ) 删除单级空⽬录,若⽬录不为空则⽆法删除,报错;相当于shell中 rmdir dirname os.listdir( 'dirname' ) 列出指定⽬录下的所有⽂件和⼦⽬录,包括隐藏⽂件,并以列表⽅式 打印 os.remove() 删除⼀个⽂件 os.rename( "oldname" , "newname" ) 重命名⽂件 / ⽬录 os.stat( 'path/filename' ) 获取⽂件 / ⽬录信息 os.system( "bash command" ) 运⾏shell命令,直接显示 os.popen("bash command).read() 运⾏shell命令,获取执⾏结果 os.getcwd() 获取当前⼯作⽬录,即当前python脚本⼯作的⽬录路径 os.chdir( "dirname" ) 改变当前脚本⼯作⽬录;相当于shell下cd # os.path 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所指向的⽂件或者⽬录的最后修改时间 os.path.getsize(path) 返回path的⼤⼩ # 特殊属性: os.sep 输出操作系统特定的路径分隔符,win下为 "\\",Linux下为" / " os.linesep 输出当前平台使⽤的⾏终⽌符,win下为 "\r\n" ,Linux下为 "\n" os.pathsep 输出⽤于分割⽂件路径的字符串 win下为;,Linux下为: os.name 输出字符串指示当前使⽤平台。win - > 'nt' ; Linux - > 'posix' os.stat() 属性解读: stat 结构: st_mode: inode 保护模式 st_ino: inode 节点号。 st_dev: inode 驻留的设备。 st_nlink: inode 的链接数。 st_uid: 所有者的⽤户 ID 。 st_gid: 所有者的组 ID 。 st_size: 普通⽂件以字节为单位的⼤⼩;包含等待某些特殊⽂件的数据。 st_atime: 上次访问的时间。 st_mtime: 最后⼀次修改的时间。 st_ctime: 由操作系统报告的 "ctime" 。在某些系统上(如Unix)是最新的元数据更改的时间,在 其它系统上(如Windows)是创建时间(详细信息参⻅平台的⽂档)。 |
例子
1 | import 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 30 31 32 33 34 35 | os.makedirs( 'dirname1/dirname5' ) # 创建文件夹目录结构 os.removedirs( 'dirname1/dirname5' ) # 删除文件夹, 如果文件夹内没有东西。 就可以删除。 否则报错 os.mkdir( 'dirname/哈哈' ) # mkdir如果父级目录不存在。 报错 os.rmdir( 'dirname' ) # 删除文件夹 print (os.listdir( '../' )) # 获取到文件夹内的所有内容. 递归 print (os.stat( 'dirname' )) # linux os.system( "dir" ) # 直接执行命令行程序 s = os.popen( "dir" ).read() print (s) print (os.getcwd() ) # 当前程序所在的文件夹 print (os.path.abspath( "../day020 继承" ) ) # 获取绝对路径 print (os.path.split( "D:\python_workspace\day020 继承" )) # 拆分路径 ('D:\\python_workspace', 'day020 继承') print (os.path.dirname( "D:\python_workspace\day020 继承" )) # D:\python_workspace print (os.path.basename( "D:\python_workspace\day020 继承" )) # day020 继承 print (os.path.exists( "dirname" )) # 判断文件是否存在 print (os.path.isabs( "D:\python_workspace\day020 继承" )) # 是否是绝对路径 print (os.path.isfile( "01 今日主要内容" )) # 是否是文件 print (os.path.isdir( "dirname" )) # 是否是文件夹 print (os.path.getsize( "01 今日主要内容" ) ) # 文件大小 print ( "胡辣汤" , "传盛" , "big" , sep = "small" ) print ( "c:" + os.sep + "胡辣汤" ) # \\/ 文件路径的分隔符 print (os.name) # nt |
六,sys模块
所有和python解释器相关的都在sys模块
1 2 3 4 5 | sys.argv 命令行参数 List ,第一个元素是程序本身路径 sys.exit(n) 退出程序,正常退出时exit( 0 ),错误退出sys.exit( 1 ) sys.version 获取Python解释程序的版本信息 sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值 sys.platform 返回操作系统平台 |
1 2 3 4 | import sys sys.exit( 1 ) # 正常退出 print (sys.version) print (sys.platform) # 平台名称 |
作业
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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | 1 、写一个copy函数,接受两个参数,第一个参数是源文件的位置,第二个参数是目标位置,将源文件copy到目标位置。 import os def copy(res, target): target_dir = os.path.dirname(target) if not os.path.exists(target_dir): # 判断父级目录是否存在 os.makedirs(target_dir) # 如果不存在就创建父级目录 with open (res, mode = "rb" ) as f1, open (target, mode = "wb" ) as f2: for line in f1: f2.write(line) copy( "e:/3000soft/hello.txt" , "f:/1111111111/fkdsajklf/fdaskfjasd/asdfas/hello.txt" ) 2 、使用random.random()来计算[m,n]以内的随机整数 ( 0 , 1 ) * 9 ( 0 , 9 ) + 2 = > [ 2 , 10 ] def func(m,n): return int (random.random() * (n - m + 1 ) + m) for i in range ( 100 ): print (func( 50 , 80 )) 3 写一个用户注册登陆的程序,每一个用户的注册都要把用户名和密码用字典的格式写入文件userinfo。 # 在登陆的时候,再从文件中读取信息进行验证。 def zhuce(): username = input ( "please input your username:" ) password = input ( "please input your password:" ) dic = { "username" : username, "password" : password} f = open ( "userinfo" , mode = "a" , encoding = "utf-8" ) f.write( str (dic) + "\n" ) f.flush() f.close() def denglu(): username = input ( "please input your username:" ) password = input ( "please input your password:" ) f = open ( "userinfo" , mode = "r" , encoding = "utf-8" ) for line in f: if line = = "": continue else : dic = eval (line.strip()) if dic[ 'username' ] = = username and dic[ 'password' ] = = password: print ( "login successful !" ) return else : print ( "login failed!!" ) denglu() 4. 新建文件 import os os.makedirs( "glance/api" ) os.makedirs( "glance/cmd" ) os.makedirs( "glance/db" ) open ( "glance/__init__.py" , mode = "w" ) open ( "glance/api/__init__.py" , mode = "w" ) open ( "glance/cmd/__init__.py" , mode = "w" ) open ( "glance/db/__init__.py" , mode = "w" ) open ( "glance/api/policy.py" , mode = "w" ) open ( "glance/api/version.py" , mode = "w" ) open ( "glance/cmd/manage.py" , mode = "w" ) open ( "glance/db/models.py" , mode = "w" ) |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· “你见过凌晨四点的洛杉矶吗?”--《我们为什么要睡觉》
· 编程神器Trae:当我用上后,才知道自己的创造力被低估了多少
· C# 从零开始使用Layui.Wpf库开发WPF客户端
· 开发的设计和重构,为开发效率服务
· 从零开始开发一个 MCP Server!