首页 > 其他分享 >py常用模块

py常用模块

时间:2023-02-03 10:36:49浏览次数:28  
标签:常用 random res py datetime json 模块 time print

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

标签:常用,random,res,py,datetime,json,模块,time,print
From: https://www.cnblogs.com/chendaodeng/p/17088304.html

相关文章

  • Pytorch_YOLO-v8-推理
    推理代码###pred_scrapt.pyfromultralyticsimportYOLOfromPILimportImageimportcv2model=YOLO("model.pt")im2=cv2.imread("bus.jpg")results=model......
  • js 时间常用方法
    newDate()获取计算机当前的日期时间.getFullYear()获取年份.getMounth()获取月份.getDate()获取日期.getHours()获取小时.getMinutes()获取分钟.getSeconds(......
  • CSS-@规则(At-rules)常用语法使用总结
    At-rules规则是目前CSS中一种常见的语法规则,它使用一个"@"符号加一个关键词定义,后面跟上语法区块,如果没有则以分号结束即可。这种规则一般用于标识文档、引入外部样式、条......
  • MDA260-16-ASEMI电源控制柜模块MDA260-16
    编辑:llMDA260-16-ASEMI电源控制柜模块MDA260-16型号:MDA260-16品牌:ASEMI封装:MDA特性:整流模块正向电流:260A反向耐压:1600V恢复时间:>500ns引脚数量:2芯片个数:2芯片尺......
  • py正则与re模块
    正则表达式符号介绍按照博客中的表格罗列的去记即可了解\w,\s,\d与\W,\S,\D相反的匹配关系(对应的两者结合就是匹配全局)\t匹配制表符\b匹配结尾的指定单词......
  • pybedtools 琐碎知识 坑
        一个坑:pybedtools使用和不用saveas会导致结果不同,有时saveas就会清空数据。 Itlookslikefilterfunctiondoesn'treturnaBedToolobject......
  • js 数字常用的方法
    Math.random()获取0~1之间的随机小数,包括0,但不包括1Math.round(数字)对输入的数字进行四舍五入Math.ceil(数字)向上取整Math.floor(数字)向下取整Math.pow(......
  • 模块的加载机制
             ......
  • py10函数之嵌套-名称空间作用域
    #函数是第一类对象:函数名指向的值可以被当中参数传递#1.函数名可以被传递#name='jason'#x=name#print(x)#print(id(x))#deffunc():#print('fromfunc')......
  • py09函数简介
     函数的返回值#deffunc():#return'asfjsfda'#res=func()#print(res)#函数内要想返回给调用者值必须用关键字return"""不写return只写return写returnNone......