码迷,mamicode.com
首页 > 其他好文 > 详细

常用模块

时间:2019-07-20 21:23:07      阅读:88      评论:0      收藏:0      [点我收藏+]

标签:python解释器   密码   datetime   pre   随机数   提示信息   切换   循环   read   

常用模块

collections模块

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

1.namedtuple: 生成可以使用名字来访问元素内容的tuple

2.deque: 双端队列,可以快速的从另外一侧追加和推出对象

3.Counter: 计数器,主要用来计数

4.OrderedDict: 有序字典

5.defaultdict: 带有默认值的字典

namedtuple具名元组

# 
# 想表示坐标点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())

OrderedDict

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)

defaultdict

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

Counter

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)

time模块

  • 打印时间戳/格式化时间/结构化时间,总而言之就是打印不同类型的时间;进行不同类型时间的转换
import time

# 时间戳
time.time()  (********)

# 格式化时间
time.strftime('%Y-%m-%d %X')

# 结构化时间
time.localtime()  # 北京时间
time.gmtime()  # 格林威治时间
time.gmtime(0)  # 1970/1/1/0:00

# 时间的转换(了解中的了解)
# 结构化时间转换为时间戳
now = time.localtime()
time.mktime(now)

# 结构化时间转格式化时间
time.strftime('%Y-%m-%d %X', now)  # 2019-06-11 08:45:30
time.strftime('%Y-%m-%d', now)  # 2019-06-11

# 格式化时间转结构化时间
now = time.strftime('%Y-%m-%d %X') 
time.strptime(now,'%Y-%m-%d %X')
time.strptime('2019|06|11', '%Y|%m|%d')

# 时间戳转化为结构化时间
now = time.time()
time.localtime(now)

# 睡眠
time.sleep(n)  # 暂停程序n秒(*****)

datetime模块

  • 时间的加减
import datetime

now = datetime.datetime.now()  # (*****)牢记

now + datetime.timedelta(3)  # +3day

now - datetime.timedelta(3)  # -3day
now + datetime.timedelta(-3)  # -3day

now + datetime.timedelta(minutes=3)  # +3minutes

now + datetime.timedelta(seconds=3)  # +3seconds

now + datetime.timedelta(365)  # +1year

now.replace(year=2012, month=12, day=22, hour=5, minute=13, second=14)
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对象 = 日期对象 +/- 日期对象
"""

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

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模块

  • 产生随机数,随机取容器元素
import random

# (0,1) (*****)
random.random()
print(random.random())  # 随机取0-1之间小数

# [1,3] 的整数 (*****)
random.randint()
print(random.randint(1,6))  # 随机取一个你提供的整数范围内的数字  包含首尾

# [1,3] 的小数
random.uniform()

# [1,3) 的整数
random.randrange()

# 取容器中的一个元素 (*****)
random.choice([1,2,3])
print(random.choice([1,2,3,4,5,6]))  # 摇号 随机从列表中取一个元素

# 取容器中的多个元素
random.sample([1,2,3],2)

# 打乱容器  (*****)
lis = [1,3,4]
random.shuffle(lis)
res = [1,2,3,4,5,6]
random.shuffle(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
l1 = [chr(i) for i in range(65,91)]
l2 = [chr(i) for i in range(97,123)]
l3 = [str(i) for i in range(10)]

l1.extend(l2)
l1.extend(l3)
def f1(n):
    suiji = random.sample(l1,n)
    res = ' '.join(suiji)
    return res
z = f1(6)
print(z)

os模块

  • 与操作系统交互,一般用来操作文件夹或文件
import os

# 新建一个文件夹
os.mkdir(path)

# 新建一个文件
f = open('','w',encoding='utf8')
f.close()

# 删除一个文件(*****)
os.remove(path)

# 重命名一个文件(*****)
os.rename(path)

# 删除空文件
os.removedirs(path)

# 删除一个空文件
os.rmdir(path)

# 拼接文件(*****)
os.path.join(path)

# 列出文件夹下所有内容(*****)
os.listdir(path)

# 获取文件大小(*****)
os.path.getsize(path)

# 获取文件夹下所有的文件夹和文件(*****)
os.walk(path)

# 当前当前项目路径
os.getcwd(path)

# 获取文件路径(*****)
os.path.dirname(os.path.dirname(__file__))

# 判断文件是否存在(*****)
os.path.exists(path)

# 执行linux命令
os.system('cd c:')

# 切换到当前所在的目录
os.chdir(path)

# 获取文件的绝对路径(*****)
os.path.abspath(__file__)  # 获取当前文件的绝对路径
os.path.abspath(path)  # 获取某一个文件的绝对路径

sys模块

  • 与python解释器交互
import sys

# 获取当前文件的环境变量,就是模块的搜索路径(*****)
sys.path
sys.path.append  # 添加环境变量

print(sys.platform)
print(sys.version)  # python解释器的版本

# 当终端  python test.py 参数1 参数2 ...  执行python文件的时候会接收参数(*****)
sys.argv  

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

序列化模块

  • 序列化
    • 序列:字符串,
    • 序列化:其他数据类型转换成字符串的过程,把数据从从内存到硬盘,对于json而言,需要按照json的标准,dict/list/str/int/float/bool(*****)
  • 反序列化:字符串转成其他数据类型,把json形式的数据从硬盘读入内存(*****)(*****)

  • 优点:跨平台性/跨语言传输数据 (*****)
  • 缺点:不能保存函数之类的数据类型,保存的类型为字符串形式

json模块

import json

# 内存中转换的
dic = {'name':'nick'}

# 了解
res = json.dumps(dic)
json.loads(res)

def write_json(filename, dic):
    with open(filename,'w',encoding='utf8') as fw:
        json.dump(dic, fw) (*****)
    
def read_json(filename):
    with open(filename,'r',encoding='utd8') as fr:
        data = json.load(fr) (*****)
    return data

d1 = {'name':'朱志坚'}
print(json.dumps(d1,ensure_ascii=False))

pickle模块

  • 优点:能存储python的任意类型数据
  • 缺点:无法跨平台,保存的数据为二进制类型
import pickle

# 内存中转换的
def func():
    pass

# 了解
res = pickle.dumps(func)
pickle.loads(res)

def write_pickle(filename, func):
    with open(filename,'wb') as fw:
        pickle.dump(func, fw) (*****)
    
def read_pickle(filename):
    with open(filename,'rb') as fr:
        data = pickle.load(fr) (*****)
    return data

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

常用模块

标签:python解释器   密码   datetime   pre   随机数   提示信息   切换   循环   read   

原文地址:https://www.cnblogs.com/zuihoudebieli/p/11219153.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!