collection,random,os,sys,序列化模块

一.collection 模块

python拥有一些内置的数据类型,比如 str,list.tuple.dict.set等

collection模块在这些内置的数据类型的基础上,提供了额外的数据类型:

  • namedtuple 具名元组 :
    •   生成可以使用名字来访问元素内容的元组
  • deque 双端队列:
    •   可以快速的从另外一侧追加和退出对象
  • Counter 计数器:
    •   主要用来计数
  • OrderedDict 有序字典:  
    •   按照键值对插入的顺序排序,不是key本身的顺序
  • defaultdict 带有默认值的字典
    • 当我使用普通的字典时,用法一般是dict={},添加元素的只需要
      dict[key] =value,调用的时候也是如此,dict[key],
      但前提是key在字典里,如果不在字典里就会报错

      这时defaultdict就能排上用场了,defaultdict的作用是在于,
      当字典里的key不存在但被查找时,返回的不是keyError而是一个默认值,

      defaultdict可以跟参数,参数可以是list、set、str,boor等等,
      作用是当key不存在时,返回的是参数的默认值,
      比如:
      list对应[ ],
      str对应的是空字符串,
      set对应set( ),
      int对应0
      boor对应False

1.namedtuple

# 想表示坐标点 x = 1, y = 2 的坐标 point
# 普通元组表示
point = (1,2)
print(point)  # >>> (1,2)  无法辨别这是一个坐标点

"""namedtuple 方法可以给元组命名"""
from collections import namedtuple

point = namedtuple('坐标',['x','y','z'])  # 第二个参数可以是可迭代带对象
# point = namedtuple('坐标','x y z')  # 第二个参数也可以是字符串,但字符串之间要用空格隔开
p = point(5,2,1)  # 注意: 传入的实参必须以定义是需要的参数个数相同
print(p)  # >>> 坐标(x=5, y=2, z=1)
# print(point(5,2,1))
print(p.x)  # >>> 5
print(p.y)  # >>> 2
print(p.z)  # >>> 1
# 可以单独打印出 传入是实参

# 例  定义扑克牌花色和大小
card = namedtuple('扑克牌','color number')
# card = namedtuple('扑克牌',['color','number'])
A = card('黑桃','A')
print(A)  # >>> 扑克牌(color='黑桃', number='A')
print(A.color)  # >>> 黑
print(A.number)  # >>> A

2.deque 

import queue
q = queue.Queue()  # 生成队列对象
# put()方法 向队列中添加值,先加入的在前面
# get()方法 从队列中取值,从第一个开始取
q.put('one')
q.put('two')
q.put('three')

print(q.get())  # >>> one
print(q.get())  # >>> two
print(q.get())  # >>> three

print(q.get())  # 如果值取完了,程序会在原地等待,直到拿到值


'''双端队列'''

from collections import deque
q = deque(['w','a','l'])
# wo = deque(('w','a','l'))
'''
append 在尾部添加
appendlift 在头部添加

pop 从尾部弹出
poplift 从头部弹出
'''
q.append(1)
q.appendleft(9)
print(q)  # >>> deque([9, 'w', 'a', 'l', 1])

print(q.pop())  # >>> 1
print(q.popleft())  # >>> 9
print(q)  # deque(['w', 'a', 'l'])

3.OrderedDict

d = dict([('a',1),('b',2),('c',3)])
print(d)  # 字典的key是无序的
# print({i for i in d})


'''OrderedDict有序字典'''

from collections import OrderedDict
oredr_d = OrderedDict([('a',1),('b',2),('c',3)])
print(oredr_d)  # >>> OrderedDict([('a', 1), ('b', 2), ('c', 3)])
order = OrderedDict()
order['x'] = 1
order['z'] = 2
order['y'] = 3
print(order)  # >>> OrderedDict([('x', 1), ('z', 2), ('y', 3)])
# print({i for i in order})  # >>> {'z', 'x', 'y'}
for i in order:
    print(i)  # 按key在字典中的顺序取出

4.defaultdict

from collections import defaultdict
values = [11, 22, 33,44,55,66,77,88,99,90]
d = defaultdict(list)  # 默认后续字典中key对应的value是列表
for i in values:
    if i > 66:
        d['key1'].append(i)
    else:
        d['key2'].append(i)
print(d)
# defaultdict(<class 'list'>, {'key2': [11, 22, 33, 44, 55, 66], 'key1': [77, 88, 99, 90]})

my_dict1 = defaultdict(int)
print(my_dict1['xxx'])
print(my_dict1['yyy'])
# 值不存在 返回 int 的默认值 0

my_dict2 = defaultdict(bool)
print(my_dict2['kkk'])
# 值不存在 返回 bool 的默认值 False

my_dict3 = defaultdict(tuple)
print(my_dict3['mmm'])
# 值不存在 返回 tuple 对应的默认值 () 空元组

my_dict4 = defaultdict(list)
print(my_dict3['www'])
# 值不存在 返回 list 对应的默认值 [] 空列表

5.Counter

# 统计:
colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']
result = {}
for color in colors:
    if result.get(color)==None:
        result[color]=1
    else:
        result[color]+=1
print (result)
# >>> {'red': 2, 'blue': 3, 'green': 1}

from collections import Counter
colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']
c = Counter(colors)
print(c)  # >>> Counter({'blue': 3, 'red': 2, 'green': 1})
print (dict(c))  # >>> {'red': 2, 'blue': 3, 'green': 1}

  

二.时间模块

  • import time
  •   time.time() 用于返回当前时间的时间戳(从1970年1月1日00时00分00秒到现在的浮点秒数)
  •   time.sleep(n) 让程序睡眠 n 秒
  •   time.strftime() 时间样式
  •         time.localtime() 格式化时间戳为本地时间
  • import datetime
  •         datetime.date.tody()  当前年月日
  •   datetime.datetime.today() 当前年月日时分秒

(******)

日期对象 = 日期对象 +/- timedelta对象
timedelta对象 = 日期对象 +/- 日期对象
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
print(time.strftime('%H:%M'))
print(time.strftime('%Y/%m'))

print(time.localtime())

print(time.localtime(time.time()))
res = time.localtime(time.time())
# print(time.time())
print(time.mktime(res))
print(time.strftime('%Y-%m',time.localtime()))
print(time.strptime(time.strftime('%Y-%m',time.localtime()),'%Y-%m'))
print(datetime.date.today())  # date>>>:年月日
print(datetime.datetime.today())  # 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就是周日
current_time = datetime.date.today()  # 日期对象
timetel_t = datetime.timedelta(days=7)  # timedelta对象
res1 = current_time+timetel_t  # 日期对象

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)

三.random随机模块

random.random()

  随机 0-1 之间的小数

random.randint()

  随机整数

random.choice()

  随机从可迭代对象中去一个数

random.shuffle()

  洗牌,打乱

print(random.random())  # 随机 0-1 之间的小数
print(random.randint(1,7))  # 随机 1-7 之间的整数,包含收尾
print(random.choice([1,2,3,4,5]))  # 随机从列表中取一个数
print(random.choice((1,2,3,5,6,7)))  # choice 的参数 需是可迭代对象
res = [1,5,2,7,9,6]
random.shuffle(res)  # 洗牌,打乱
print(res)
up_res = chr(random.randint(65,90))  # 按ASCII码表随机取一个大写字母
print(up_res)
low_res = chr(random.randint(97,122)) # 按ASCII码表随机取一个小写字母
print(low_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(5)
print(res)

 四 os模块

  os模块是与操作系统打交道

1 os.listdir()

  以列表的形式返回所指定文件下的所有文件夹和文件

print(os.listdir(r'D:\python视频\day16\代码\day16\老师们的作品'))
# >>> ['tank老师.txt', '冲老师.txt', '明老师.txt', '波老师.txt', '田老师.txt', '苍老师.txt']

2 os.path.dirname(__file__)

  获取当前所在py文件的文件夹路径(绝对路径)

BASE_DIR = os.path.dirname(__file__)
print(BASE_DIR) # >>> D:/python视频/day16/代码/day16

3 os.path.join()

  拼接绝对路径

join_dir = os.path.join(BASE_DIR,'老师们的作品')
print(join_dir)  # >>> D:/python视频/day16/代码/day16\老师们的作品

4 os.mkdir()

  自动创建文件夹(在当前py文件的文件夹下创建)

 5 os.path.exists()

  判断文件或文件夹 是否在指定的路径下

print(os.path.exists(r'D:\python脱产10期视频\day16\代码\day16\老师们的作品'))  # >>> True
print(os.path.exists(r'D:\python脱产10期视频\day16\代码\day16\老师们的作品\tank老师.txt'))  # >>> True

6 os.path.isfile()

  只判断文件夹 是否在指定的路径下

print(os.path.isfile(r'D:\python脱产10期视频\day16\代码\day16\老师们的作品'))  # >>> False
print(os.path.isfile(r'D:\python脱产10期视频\day16\代码\day16\老师们的作品\tank老师.txt')) # >>> True

 7 os.path.rmdir()

  删除指定路径的文件夹 只删除空文件 

os.rmdir(r'D:\Python项目\day16\老师们的作品')  # 只能删空文件夹

 8 os.getcwd()

  打印当前py文件所在的文件夹路径,与 dirname 相同

print(os.getcwd())# 打印当前py文件所在的文件夹路径
# >>> D:\python脱产10期视频\day16\代码\day16

9 os.chdir()

  切换到指定的文件夹路径

print(os.chdir(r'D:\python脱产10期视频\day16\代码\day16\老师们的作品'))  # 切换到指定的文件夹路径
print(os.getcwd()) # 与 chdir 和用,打印出所切换到的文件夹路径
# >>> D:\python视频\day16\代码\day16\老师们的作品

10 os.path.getsize()

  获取文件大小(字节数)

print(os.path.getsize(r'D:\python脱产10期视频\day16\代码\day16\老师们的作品\tank老师.txt'))  # 字节大小(个数)
with open(r'D:\python脱产10期视频\day16\代码\day16\老师们的作品\tank老师.txt',encoding='utf-8') as f:
    print(len(f.read()))  # 字符个数

五.sys模块 

  sys模块是与python解释器打交道

1 sys.path.append() 

  将某个路径添加到系统环境变量中

BASE_DIR = os.path.dirname(os.path.dirname(__file__))  
# print(BASE_DIR)
sys.path.append(BASE_DIR)

 2 sys.platform

  电脑的系统配置

 3 sys.version

  python 解释器版本

 4 sys.argv

  获取当前py文件的绝对路径,且以list形式返回

print(sys.argv)  # 命令行启动文件 可以做身份的验证
# ['D:/python脱产10期视频/day16/代码/day16/06 sys模块.py']

 六.序列化模块

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

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

 1 json模块

  只支持的数据类型:

    字符串 列表 字典 整形 元组(转成列表) 布尔值

  优点:所有的语言都支持json格式

  缺点:支持的数据类型很少

dumps:序列化 将其他数据类型转成json格式的字符串
loads:反序列化 将json格式的字符串转换成其他数据类型
res = json.dumps(d)  # json格式的字符串 必须是双引号 >>>: '{"name": "jason"}'
print(res,type(res))  # >>> {"name": "jason"} <class 'str'>
res1 = json.loads(res)  # 将 json 字符串格式的字典转成 字典
print(res1,type(res1))  # >>> {'name': 'jason'} <class 'dict'>

dump 针对文件操作 把字典转成json字符串并写入到文件
load 针对文件操作 把文件中以json字符串形式存的内容反序列化读出来
d = {"name":"json"} # 字典
with open('userinfo','w',encoding='utf-8') as f:
    json.dump(d,f)  # 转字符串形式的字典并自动写入文件 {"name": "json"} <class 'str'>
with open('userinfo','r',encoding='utf-8') as f:
    res = json.load(f)  # {'name': 'json'}<class 'dict'>
    print(res,type(res))

 2 pickle模块

  缺点:只支持python

  优点:python的所有的数据类型都支持

 dumps 将数据序列化成二进制格式 ()可解码符内容)

 loads 反序列化

d = {'name':'json'}
res = pickle.dumps(d)  # 将对象直接转成二进制
print(pickle.dumps(d))
res1 = pickle.loads(res)
print(res1,type(res1))

 dump 针对文件操作 把数据序列化成二进制并写入到文件

 load 针对文件操作 把文件中以pickle形式存的二进制内容反序列化读出来

   用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))

七.subprocess子进程

1.用户通过网络连接上了你的这台电脑
2.用户输入相应的命令 基于网络发送给了你这台电脑上某个程序
3.获取用户命令 里面subprocess执行该用户命令
4.将执行结果再基于网络发送给用户
这样就实现 用户远程操作你这台电脑的操作
while True:
    cmd = input('cmd>>>:').strip()
    import subprocess
    obj = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    # print(obj)
    print('正确命令返回的结果stdout',obj.stdout.read().decode('gbk'))
    print('错误命令返回的提示信息stderr',obj.stderr.read().decode('gbk'))

猜你喜欢

转载自www.cnblogs.com/waller/p/11210859.html