d16 collections模块 时间模块 random模块 os模块 sys模块 序列化模块 subprocess模块

 

collections模块

在内置数据类型(dict、list、set、tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter、deque、defaultdict、namedtuple和OrderedDict等。

nametype具名元组

具有名字的元组

坐标 :x为1 y为2 z为3

from collections import namedtuple
point = namedtuple('坐标',['x','y','z'])
#也可以下面格式
point1 = namedtuple('坐标','x, z, y')
# 第二个参数既可以为可迭代对象,也可以是字符串
# 字符串得用空格隔开
p = point(1,2,3)
# 注意元素的个数必须和nametype第二个参数的数量一致
print(p)
print(p.x)
print(p.y)
print(p.z)
View Code

扑克牌

from collections import namedtuple

card= namedtuple('扑克牌','color,number')
# card= namedtuple('扑克牌',['color,number'])
A = card('','A')
print(A)
print(A.color)
print(A.number)
View Code

城市天气

city  = namedtuple('中国','city,weather,temperature')
c = city('北京','','30')
print(c)
print(c.city)
print(c.weather)
print(c.temperature)
View Code
deque双端队列

双端队列俩端都可以进和出

queue队列

队列:先进先出,  FIFO(first in first out)
import queue
# 生成队列对象
q = queue.Queue()
# 往队列添加值
q.put('first')
q.put('second')
q.put('third')

# 向队列取值,程序会在原地等待,直到从队列获得值
print(q.get())
print(q.get())
print(q.get())
View Code

deque双端队列

from collections import deque
q = deque(['a','b','c'])
# 添加值
q.append('1')
# 左添加值
q.appendleft('2')
print(q)
# 取值
print(q.pop())
#取左值
#特殊点   可以根据索引在任意位置插入值
q.insert(2,'哈哈')
q.insert(4,'嘿嘿')
View Code

队列不应该支持在任意位置插入值,只能在首尾插值

语法

插入
insert
添加
append
appendleft
取值
pop
popleft
View Code
OrderedDict有序字典

普通字典

normal_d = dict([('a',1),('b',2),('c',3)])
print(normal_d)
normal_d['q'] = 11
normal_d['w'] = 22
print(normal_d)
View Code

有序字典

from collections import OrderedDict
order_d = OrderedDict([('a',1),('b',2),('c',3)])
print(order_d)
order_d1 = OrderedDict()
order_d1['x'] = 11
order_d1['y'] = 22
order_d1['z'] = 33
print(order_d1)
for i in order_d1:
    print(i)
View Code

OrderedDict的Key会按照插入的顺序排列,不是Key本身排序

defaultdict 默认字典

一般写法

value = [11,22,33,44,55,66,77,88,99]

将所有大于 66` `的值保存至字典的第一个'key'中,将小于 66` `的值保存至第二个'key'的值中。
values = [11, 22, 33,44,55,66,77,88,99,90]

my_dict = {}

for value in  values:
    if value>66:
        if my_dict.has_key('k1'):
            my_dict['k1'].append(value)
        else:
            my_dict['k1'] = [value]
    else:
        if my_dict.has_key('k2'):
            my_dict['k2'].append(value)
        else:
            my_dict['k2'] = [value]
View Code

使用模块

from collections import defaultdict

values = [11, 22, 33,44,55,66,77,88,99,90]

my_dict = defaultdict(list)  # 后续该字典中新建的key对应的value默认就是列表
print(my_dict['aaa'])
for value in  values:
    if value>66:
        my_dict['k1'].append(value)
    else:
        my_dict['k2'].append(value)
print(my_dict)


my_dict1 = defaultdict(int)
print(my_dict1['xxx'])
print(my_dict1['yyy'])

my_dict2 = defaultdict(bool)
print(my_dict2['kkk'])

my_dict3 = defaultdict(tuple)
print(my_dict3['mmm'])
View Code

使用'dict'时,如果引用的'Key'不存在,就会抛出'KeyError'。如果希望'key'不存在时,返回一个默认值,就可以用'defaultdict'

>>> from collections import defaultdict
>>> dd = defaultdict(lambda: 'N/A')
>>> dd['key1'] = 'abc'
>>> dd['key1'] # key1存在
'abc'
>>> dd['key2'] # key2不存在,返回默认值
'N/A'
View Code
counter 计数

Counter类的目的是用来跟踪值出现的次数。它是一个无序的容器类型,以字典的键值对形式存储,其中元素作为key,其计数作为value。计数值可以是任意的Interger(包括0和负数)

一般写法

s = 'asdfghjkhgfdsawssadfghjhhfgdsdsdag'
a = {}
for i in s:
    print(i)
    a[i] = 0
# 在就加1
print(a)
View Code

使用模块

from collections import Counter
s = 'asdfghjkhgfdsawssadfghjhhfgdsdsdag'
a = {}
res = Counter(s)
print(Counter)
print(res)
# 得到了v值
for q in res.values():
    print(q)
View Code

时间模块

表现时间的三种方式
1.时间戳(timestamp)
2.格式化时间(format string)
3.结构化时间(struct_time)
%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 当前时区的名称
%% %号本身
time模块
import time
时间戳
time.time()
格式化时间
print(time.strftime('%Y-%m-%d'))
print(time.strftime('%Y-%m-%d %H:%M:%S'))
print(time.strftime('%Y-%m-%d %X'))  
# %X等价于%H:%M:%S
时间元组
localtime将一个时间戳转换为当前时区的struct_time
time.localtime()
View Code

时间戳是计算机能够识别的时间;时间字符串是人能够看懂的时间;元组则是用来操作时间的

转换时间

时间戳-->结构化时间
time.gmtime(时间戳)    
time.localtime(时间戳)

>>>time.gmtime(1500000000)
time.struct_time(tm_year=2017, tm_mon=7, tm_mday=14, tm_hour=2, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=0)
>>>time.localtime(1500000000)
time.struct_time(tm_year=2017, tm_mon=7, tm_mday=14, tm_hour=10, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=0)
时间戳-->结构化时间
结构化时间-->时间戳 
time.mktime(结构化时间)
>>>time_tuple = time.localtime(1500000000)
>>>time.mktime(time_tuple)
1500000000.0
结构化时间-->时间戳
结构化时间-->字符串时间
time.strftime("格式定义","结构化时间")  结构化时间参数若不传,则显示当前时间
>>>time.strftime("%Y-%m-%d %X")
'2017-07-24 14:55:36'
>>>time.strftime("%Y-%m-%d",time.localtime(1500000000))
'2017-07-14'
结构化时间-->字符串时间
字符串时间-->结构化时间
time.strptime(时间字符串,字符串对应格式)
>>>time.strptime("2017-03-16","%Y-%m-%d")
time.struct_time(tm_year=2017, tm_mon=3, tm_mday=16, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=75, tm_isdst=-1)
>>>time.strptime("07/24/2017","%m/%d/%Y")
time.struct_time(tm_year=2017, tm_mon=7, tm_mday=24, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=205, tm_isdst=-1)
字符串时间-->结构化时间

结构化时间 --> %a %b %d %H:%M:%S %Y串
time.asctime(结构化时间) 如果不传参数,直接返回当前时间的格式化串
>>>time.asctime(time.localtime(1500000000))
'Fri Jul 14 10:40:00 2017'
>>>time.asctime()
'Mon Jul 24 15:18:33 2017'

时间戳 --> %a %b %d %H:%M:%S %Y串
time.ctime(时间戳)  如果不传参数,直接返回当前时间的格式化串
>>>time.ctime()
'Mon Jul 24 15:19:07 2017'
>>>time.ctime(1500000000)
'Fri Jul 14 10:40:00 2017' 
View Code
datetime模块
import datetime
print(datetime.date.today())  
# date>>>:年月日
print(datetime.datetime.today())  
# datetime>>>:年月日 时分秒
模块
import datetime
res = datetime.date.today()
res1 = datetime.datetime.today()
print(res.year)
print(res.month)
print(res.day)
print(res.weekday())  # 0-6表示星期  0表示周一
print(res.isoweekday())  # 1-7表示星期 7就是周日
语法
日期对象 = 日期对象 +/- timedelta对象
timedelta对象 = 日期对象 +/- 日期对象

current_time = datetime.date.today()  # 日期对象
timetel_t = datetime.timedelta(days=7)  # timedelta对象
# +
res1 = current_time+timetel_t  # 日期对象
print(current_time)
print(timetel_t)
print(res1)
# -
print(current_time - timetel_t)
print(res1-current_time)
加减时间

小练习 计算今天距离今年过生日还有多少天

birth = datetime.datetime(2019,12,21,8,8,8)
current_time = datetime.datetime.today()
print(birth-current_time)
练习
# UTC时间
dt_today = datetime.datetime.today()
dt_now = datetime.datetime.now()
dt_utcnow = datetime.datetime.utcnow()
print(dt_utcnow,dt_now,dt_today)
UTC时间

random模块

import random
整数
random.randint(1,10)
# 随机取一个数字
random.randrange(1,10,2) 
# 大于等于1且小于10之间的奇数
小数
random.random()
# 随机取0-1的小数
random.uniform(1,3) 
#大于1小于3的小数
随机选择值返回
random.choice([1, 2, 3, 4, 5, 6,7])
# 随机从列表取值
random.sample([1,'2',[3,4]],9) # #列表元素任意2个组合
语法
res = [1, 2, 3, 4, 5, 6,7]
random.shuffle(res)
print(res)
打乱顺序,洗牌

随机验证码

大写字母 小写字母 数字

5位数的随机验证码
chr
random.choice
封装成一个函数,用户想生成几位就生成几位
要求
def get_code(n):
    code = ''
    for i in range(n):
        # 先生成随机的大写字母 小写字母 数字
        upper_str = chr(random.randint(65,90))
        lower_str = chr(random.randint(97,122))
        random_int = str(random.randint(0,9))
        # 从上面三个中随机选择一个作为随机验证码的某一位
        code += random.choice([upper_str,lower_str,random_int])
    return code
res = get_code(4)
print(res)
代码

os模块

 os模块是与操作系统交互的一个接口

import os
listdir  会将当前文件夹的文件展示出来
os.mkdir   自动创建文件夹
os.path.exists   判断文件夹是否存在
os.path.isfile    只能判断文件是否存在,不能判断文件夹

remove  删除文件
os.rmdir     删除单级目录,只能删除空文件夹
os.getcwd()  获取目录
os.chdir()  切换当前所在目录
os.path.getsize()    获取文件大小  大小单位为字节
常用语法

语法

os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
os.chdir("dirname")  改变当前脚本工作目录;相当于shell下cd
os.curdir  返回当前目录: ('.')
os.pardir  获取当前目录的父目录字符串名:('..')
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.sep    输出操作系统特定的路径分隔符,win下为"\",Linux下为"/"
os.linesep    输出当前平台使用的行终止符,win下为"	
",Linux下为"
"
os.pathsep    输出用于分割文件路径的字符串 win下为;,Linux下为:
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所指向的文件或者目录的最后修改时间
os.path.getsize(path) 返回path的大小
综合

练习

选择文件查看

文件夹
火影人物
    鸣人.txt
    向日宁次.txt
    卡卡西.txt
    我爱罗.txt
    大蛇丸.txt
    波佐助.txt
import os
BASE_DIR = os.path.dirname(__file__)
MOVIE_DIR = os.path.join(BASE_DIR,'火影人物')
movie_list = os.listdir(MOVIE_DIR)
while True:
    for i,j in enumerate(movie_list,1):
        print(i,j)
    choice = input('你想看谁的啊(小姑娘/小伙子)>>>:').strip()
    if choice.isdigit():  # 判断用户输入的是否是纯数字
        choice = int(choice)  # 传成int类型
        if choice in range(1,len(movie_list)+1):  # 判断是否在列表元素个数范围内
            # 获取用户想要看的文件名
            target_file = movie_list[choice-1]
            # 拼接文件绝对路径
            target_path = os.path.join(MOVIE_DIR,target_file)
            with open(target_path,'r',encoding='utf-8') as f:
                print(f.read())
            else:
            print('所选不在名单中')
    else:
        print('输入数字哦')
代码

sys模块

sys模块是与python解释器交互的一个接口

sys.argv           命令行参数List,第一个元素是程序本身路径
sys.exit(n)        退出程序,正常退出时exit(0),错误退出sys.exit(1)
sys.version        获取Python解释程序的版本信息
sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform       返回操作系统平台名称
语法
mport sys
# sys.path.append()  # 将某个路径添加到系统的环境变量中
# print(sys.platform)
# print(sys.version)  # python解释器的版本

print(sys.argv)  # 命令行启动文件 可以做身份的验证
if len(sys.argv) <= 1:
    print('请输入用户名和密码')
else:
    username = sys.argv[1]
    password = sys.argv[2]
    if username == 'jason' and password == '123':
        print('欢迎使用')
        # 当前这个py文件逻辑代码
    else:
        print('用户不存在 无法执行当前文件')
例子

序列化模块

序列化:
 序列:字符串
 序列化:其它数据类型转换成字符串的过程

写入文件的数据必须是字符串
基于网络传输的数据必须是二进制

序列化:其他数据类型转换成字符穿的过程
反序列化:字符串转换成其他数据类型

目的:

1、以某种存储形式使自定义[对象持久化](https://baike.baidu.com/item/%E5%AF%B9%E8%B1%A1%E6%8C%81%E4%B9%85%E5%8C%96);

2、将对象从一个地方传递到另一个地方。

3、使程序更具维护性。

  

json模块
    所有的语言都支持json格式
    支持的数据类型很少  字符串 列表 字典 整型 元组(转成列表)  布尔值

pickle模块
    只支持python
    python所有的数据类型都支持
    
json,用于字符串 和 python数据类型间进行转换
pickle,用于python特有的类型 和 python的数据类型间进行转换
json模块
json.dumps()
序列化 将其他数据类型转换成json格式的字符串
json.dump()
dump方法接收一个文件句柄,直接将字典转换成json字符串写入文件
json.loads()
反序列化 将json格式的字符串转换成其他数据类型
json.load()
load方法接收一个文件句柄,直接将文件中的json字符串转换成数据结构返回
注意,json转换完的字符串类型的字典中的字符串是由""表示的

 

d = {"name":"jason"}
print(d)
#序列化:将一个字典转换成一个字符串
res = json.dumps(d)  # json格式的字符串 必须是双引号 >>>: '{"name": "jason"}'
print(res,type(res))

#反序列化:将一个字符串格式的字典转换成一个字典
res1 = json.loads(res)
print(res1,type(res1))
例子
d = {"name":"jason"}

with open('userinfo','w',encoding='utf-8') as f:
    json.dump(d,f)  # 装字符串并自动写入文件
with open('userinfo','r',encoding='utf-8') as f:
    res = json.load(f)
    print(res,type(res))
    
with open('userinfo','r',encoding='utf-8') as f:
    res1 = json.load(f)  # 不能够多次反序列化
    res2 = json.load(f)
    print(res1,type(res1))
    print(res2,type(res2))
    

with open('userinfo','w',encoding='utf-8') as f:
    json_str = json.dumps(d)
    json_str1 = json.dumps(d)
    #换行写
    f.write('%s
'%json_str)
    f.write('%s
'%json_str1)

#换行读
with open('userinfo','r',encoding='utf-8') as f:
    for line in f:
        res = json.loads(line)
        print(res,type(res))
t = (1,2,3,4)
print(json.dumps(t))

# fp = 文件句柄(对象)
在源码中fp =文件句柄(对象) 
练习

ensure_ascii 是否转码

有中文时,使用
d1 = {'name':'熊大'}
print(json.dumps(d1,ensure_ascii=False))
View Code
pickle模块
dumps、dump(序列化,存)、
loads(反序列化,读)、load  (不仅可以序列化字典,列表...可以把python中任意的数据类型序列化)

 

import pickle
d = {'name':'jason'}
res = pickle.dumps(d)  # 将对象直接转成二进制
print(pickle.dumps(d))
res1 = pickle.loads(res)
print(res1,type(res1))
例子
用pickle操作文件的时候 文件的打开模式必须是b模式 
with open('userinfo_1','wb') as f:
    pickle.dump(d,f)

with open('userinfo_1','rb') as f:
    res = pickle.load(f)
    print(res,type(res))
例子

subprucess子进程

1.用户通过网络连接上了你的这台电脑
2.用户输入相应的命令 基于网络发送给了你这台电脑上某个程序
3.获取用户命令 里面subprocess执行该用户命令
4.将执行结果再基于网络发送给用户
这样就实现  用户远程操作你这台电脑的操作
实现
import subprocess
 执行系统指令
import os
# dir 列出所有进程
os.system('dir')


# 打开进程
# shell 命令解释器
# stdout  标准输出
# 指定输出管道
stdout=subprocess.PIPE

a=subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE)

# 从管道中读取出执行结果
#[1] 输出
a1=subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE )
print(a1.stdout.read().decode('GBK'))

# [2] 输入
a1=subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE,stdin= subprocess.PIPE)

# PIPE 大写的单词为常量
# PIPE = -1
# STDOUT = -2
# DEVNULL = -3
# [3] 错误输出
print(a1.stderr .read().decode('utf-8'))
# tasklist | findstr python
#  先执行tasklist 把结果交给 findstr 来处理

把p1的输出传给p2,
p1 = subprocess.Popen("tasklist",shell=True,stdout=subprocess.PIPE)

p2 = subprocess.Popen('findstr QQ',shell=True,stdin=p1.stdout,stdout=subprocess.PIPE,stderr= subprocess.PIPE )


print(p2.stdout.read())
print(p2.stderr.read())
# 参数1 指令
# p = subprocess.Popen("你的指令或是某个exe",shell=True,stderr=,stdin=,stdout=)

# 2 是否是一个指令
# 3 错误输出管道
# 4 输入管道
# 5 输出管道
# # 取出管道中的数据
# p.stderr.read()
# p.stdout.read()
# p.stdin.write(p.stdout.read())#
#  将输入写入管道 交给对方进程
语法
原文地址:https://www.cnblogs.com/komorebi/p/11210204.html