02 collection模块

# 具名元组
# 想表示坐标点x为1 y为2的坐标
from collections import namedtuple
# point = namedtuple('坐标',['x','y','z']) # 第二个参数既可以传可迭代对象
# point = namedtuple('坐标','x y z') # 也可以传字符串 但是字符串之间以空格隔开
# p = point(1,2,5) # 注意元素的个数必须跟namedtuple第二个参数里面的值数量一致
# print(p)
# print(p.x)
# print(p.y)
# print(p.z)

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

# city = namedtuple('日本','name person size')
# c = city('东京','R老师','L')
# print(c)
# print(c.name)
# print(c.person)
# print(c.size)

# 队列:现进先出(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())
# print(q.get()) # 如果队列中的值取完了 程序会在原地等待 直到从队列中拿到值才停止

# deque双端队列
# from collections import deque
# q = deque(['a','b','c'])
# """
# append
# appendleft
#
# pop
# popleft
# """
# q.append(1)
# q.appendleft(2)
#
# """
# 队列不应该支持任意位置插值
# 只能在首尾插值(不能插队)
# """
# q.insert(0,'哈哈哈') # 特殊点:双端队列可以根据索引在任意位置插值
# print(q.pop())
# print(q.popleft())
# print(q.popleft())

# normal_d = dict([('a',1),('b',2),('c',3)])
# print(normal_d)
# from collections import OrderedDict
# order_d = OrderedDict([('a',1),('b',2),('c',3)])
# order_d1 = OrderedDict()
# order_d1['x'] = 1
# order_d1['y'] = 2
# order_d1['z'] = 3
# print(order_d1)
# for i in order_d1:
# print(i)
# # print(order_d1)
# # print(order_d)
# order_d1 = dict()
# order_d1['x'] = 1
# order_d1['y'] = 2
# order_d1['z'] = 3
# print(order_d1)
# for i in order_d1:
# print(i)

# 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'])

# from collections import Counter
# s = 'abcdeabcdabcaba'
# res = Counter(s)
# print(res)
# for i in res:
# print(i)
# 先循环当前字符串 将每一个字符串都采用字典新建键值对的范式
# d = {}
# for i in s:
# d[i] = 0
# print(d)

03 时间模块

# time
"""
三种表现形式
1.时间戳
2.格式化时间(用来展示给人看的)
3.结构化时间
"""
import time
# print(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
# 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'))

# datetime
import datetime
# 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就是周日
"""
(******)
日期对象 = 日期对象 +/- timedelta对象
timedelta对象 = 日期对象 +/- 日期对象
"""
# 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)

04 random模块

# 随机模块
import random

# print(random.randint(1,6)) # 随机取一个你提供的整数范围内的数字 包含首尾
# print(random.random()) # 随机取0-1之间小数
# print(random.choice([1,2,3,4,5,6])) # 摇号 随机从列表中取一个元素
# res = [1,2,3,4,5,6]
# 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)

# 随机模块
import random

# print(random.randint(1,6)) # 随机取一个你提供的整数范围内的数字 包含首尾
# print(random.random()) # 随机取0-1之间小数
# print(random.choice([1,2,3,4,5,6])) # 摇号 随机从列表中取一个元素
# res = [1,2,3,4,5,6]
# 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模块:跟操作系统打交道的模块
# sys模块:跟python解释器打交道模块

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('你想看谁的啊(今日热搜:tank老师)>>>:').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())

# os.mkdir('tank老师精选') # 自动创建文件夹
# print(os.path.exists(r'D:\Python项目\day16\rion老师精选')) # 判断文件是否存在
# print(os.path.exists(r'D:\Python项目\day16\老师们的作品\tank老师.txt')) # 判断文件是否存在
# print(os.path.isfile(r'D:\Python项目\day16\tank老师精选')) # 只能判断文件 不能判断文件夹
# print(os.path.isfile(r'D:\Python项目\day16\老师们的作品\tank老师.txt')) # 只能判断文件 不能判断文件夹

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

# print(os.getcwd())
# print(os.chdir(r'D:\Python项目\day16\老师们的作品')) # 切换当前所在的目录
# print(os.getcwd())

# 获取文件大小
# print(os.path.getsize(r'D:\Python项目\day16\老师们的作品\tank老师.txt')) # 字节大小
# with open(r'D:\Python项目\day16\老师们的作品\tank老师.txt',encoding='utf-8') as f:
# print(len(f.read()))

import 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('用户不存在 无法执行当前文件')

07 序列化模块

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

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

d = {'name':'jason'} 字典
str(d)

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

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

pickle模块(****)
只支持python
python所有的数据类型都支持
"""
import json
"""
dumps:序列化 将其他数据类型转成json格式的字符串
loads:反序列化 将json格式的字符串转换成其他数据类型

dump load
"""
# 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','w',encoding='utf-8') as f:
# json.dump(d,f) # 装字符串并自动写入文件
# json.dump(d,f) # 装字符串并自动写入文件

# 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\n'%json_str)
# f.write('%s\n'%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))

# d1 = {}
# print(json.dumps(d1,ensure_ascii=False))

# pickle
# 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))

08 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'))

最新文章

  1. D2js 是如何处理并发的
  2. Head First 设计模式--1策略模式 组合优于继承
  3. X3DOM 1.6.1 发布注记
  4. DHTMLX 前端框架 建立你的一个应用程序教程(三)--添加一个菜单
  5. 23个经典JDK设计模式(转)
  6. 图片样式 scaleType 属性
  7. NOI2015
  8. Android应用中使用Popupmenu
  9. ssh整合启动tomcat报java.lang.ClassNotFoundException: org.apache.commons.lang.xwork.StringUtils
  10. 基于TcpListener实现最简单的http服务器
  11. sql 上舍下舍運用
  12. Linux 防火墙:Netfilter iptables
  13. linux设置自动更换壁纸
  14. POJ.1704.Georgia and Bob(博弈论 Nim)
  15. 用vue构建多页面应用
  16. 解决maven 找不到指定路径应该如何
  17. PAT天梯:L1-019. 谁先倒
  18. UIButton的两种block传值方式
  19. STL sort 函数实现详解 ZZ
  20. RichTextBox 清空

热门文章

  1. JavaSE 对象与类(一)
  2. adb+monkey常用命令记录升级版
  3. 关于vue组件传值和事件绑定问题
  4. pyinstaller打包Python程序报错OSError: Python library not found: libpython3.8.so, libpython3.8m.so
  5. 2.6 EmpController
  6. Visual Studio 2017(vs2017)绿色便携版-北桃特供
  7. elasticsearch别名
  8. foreach 和for
  9. ubuntu下安装lua和tolua++
  10. 10. watch的实现原理