zoukankan      html  css  js  c++  java
  • 常用模块以及方法

    今日内容:


     

    collectiont模块\time模块\datetime模块\os模块\random模块\json模块\pickle模块\subprocess模块

    待补充 :hashlib模块(加密模块)\包\logging模块\configpaese模块\openpyxl模块

     

    collectiont模块:


     

     

    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,z)
    
    print(p,x)
    
    print(p,y)
    
    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)
    collections与namedtuple的应用

    deque双端队列:


     

    队列: 先进先出(FIFO first in first out)

    import queue
    
    q = queue.Queue()  # 生成队列对象
    
    q.put('first')  # 往队列中添加值
    
    q.put('second')
    
    q.put('third')
    
    print(q.get())  # first
    
    print(q.get())  # second
    
    print(q.get())  # third
    
    print(q.get())  # 朝队列要值,如果队列中的值取完了,程序会在原地等待,直到从队列中拿到值

    collections与deque的应用

    from collertions import deque
    
    q = deque(['a','b','c'])
    
    '''
    append在右边插入
    appendleft在左边插入
    pop从右边弹出
    popleft从左边弹出
    '''
    
    q.append(1)
    
    q.appendleft(2)
    
    print(q.pop())  # 1
    
    print(q.popleft())  # 2
    
    '''
    队列不应该支持任意位置插值
    只能在首位插值(不能插队)
    '''
    
    q.insert(1,'哈哈哈')  # 特殊点:双端队列可以根据索引在任意位置插值
    
    print(q.pop())  # 1
    
    print(q.popleft())  # 哈哈哈
    
    print(q.popleft())  # 2
    collections与deque的应用

    OrderedDict有序字典:


     

    normal_d = dict([('a',1),('b',2),('c',3)])
    
    print(normal_d)  # {'a': 1, 'b': 2, 'c': 3}
    
    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)  # OrderedDict([('x', 1), ('y', 2), ('z', 3)])
    
    for i in order_d1:
    
        print(i)  # x,y,z
    
    print(order_d)  # OrderedDict([('a', 1), ('b', 2), ('c', 3)])

    defaultdict默认值字典:


     

    from collections import defaultdict
    
    values = [11,22,33,44,55,66,77,88,99,900]
    
    my_dict = defaultdict(list)  # 后续该字典中新建的key对应的value默认就是列表
    
    for value in values:
    
        if value > 66:
    
            my_dict['k1'].append(value)
    
        else:
    
            my_dict['k2'].append(value)
    
    print(my_dict)  # defaultdict(<class 'list'>, {'k2': [11, 22, 33, 44, 55, 66], 'k1': [77, 88, 99, 900]})

    如果指定用int类型返回值,又选择字典中不存在的key值:

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

    如果指定用bool类型返回值,又选择字典中不存在的key值:

    ​my_dict2 = defaultdict(bool)
    
    print(my_dict2['xxx'])  # False

    counter:计数器

    from collections import Counter
    
    s = 'abcdeabcdabcaba'
    
    '''
    如果不想用模块的知识点

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

    time时间模块:


     

     

    time:


     

    time有三种表现形式:

    1.时间戳 Timestamp

    import time
    
    print(time.time())  # 与unix元年相距多少秒

    2.格式化时间(用来展示给人看的) Format string

    import time
    
    print(time.strftime('%Y-%m-%d'))    #  2019-07-18
    
    print(time.strftime('%Y-%m-%d %H:%M:%S'))  # 2019-07-18 11:25:30
    
    print(time.strftime('%Y-%m-%d %X'))  # 2019-07-18 11:25:30,即%X等价于%H:%M:%S

    3.结构化时间 struct_time

    import time
        
    print(time.localtime())        

    三者之间的结构关系(图):

    # 下面的代码主要是展示它们之间的区别
    
    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'))
    time三种表现形式之间的关系

    datetime:


     

    import datetime
    
    print(datetime.date.today())  # date>>>:年月日
    
    print(datetime.datetime.today())  # datetime>>>:年月日 时分秒
    
    res = datetime.date.today()
    
    res1 = datetime.datetime.today()
    
    print(res.year)  # 返回结果为:2019
    
    print(res.month)  # 返回结果为:7
    
    print(res.day)  # 返回结果为:18
    
    print(res.weekday)  # <built-in method weekday of datetime.date object at 0x000001D48DC07B70>
    
    print(res.weekday())  # 返回结果为:3,若0~6表示星期,则0表示周一;若1~7表示星期,则7就是周日

    拓展:timetel_ttimedelta

    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)

    关键点:

    • 日期对象 = 日期对象 +/- timedelta对象
    • timedelta对象 = 日期对象 +/- 日期对象
    举例:计算今天举例今年过生日还有多少天
    # 只显示年月日
    birth = datetime.date(2019,12,21)
    
    current_time = datetime.date.today()
    
    print(birth-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)  # 2019-07-18 09:56:36.925833 2019-07-18 17:56:36.925833 2019-07-18 17:56:36.925833

    random模块:


     

    关于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,且封装成一个函数,用户想生成几位就生成几位

    import random
    
    def get_code(n)
    
        code = ' '
    
        for i in range(n):
    
            # 先生成随机的大写母子,小写字母,数字
            upper_str = chr(random.ranint(65,90))
    
            lower_str = chr(random.ranint(97,122))
    
            random_int = str(random.randomint(0,9))
    
            # 从上面三段代码中随机选择一个作为随机验证码的某一位
            code += random.choice([upper_str,lower_str,random.int])
    
        return code  # 返回的是随机生成的验证码
    
    res = get_code(4)
    
    print(res)

    os模块:


     

    定义:跟操作系统打交道的模块

    下面介绍一些os模块中的方法:

    import os
    
    BASE_DIR = os.path.dirname(__file__)
    
    MOVIE_DIR = os.path.join(BASE_DIR,'老师们的作品')
    
    movie_list = os.listdir(MOVIE_DIR)
    
    print(os.listdir(r'copy_pyth'))  # 将文件夹中所有文件名以列表形式打印出来
    
    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'copy_path'))  # 判断文件是否存在
    
    print(os.path.isfile(r'copy_path'))  # 只能判断文件,无法判断文件夹
    
    ​
    os.rmdir(r'copy_path')  # 只能删空文件夹
    print(os.getcwd())  # 查看当前目录
    
    print(os.chdir(r'copy_path'))  # 切换当前所在的目录
    # 获取文件大小
    print(os.path.getsize(r'copy_path'))  # 打印字节大小
    
    with open(r'copy_path', encoding='utf-8') as f:
    
        print(len(f.read()))

    sys模块:


     

    定义:跟python解释器打交道的模块

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

    序列化模块:


     

    序列:字符串

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

    • 写入文件的数据必须是字符串
    • 基于网络传输的数据必须是二进制(str.encode())

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

    json模块:


     

    优缺点:

    • 优点:所有的语言都支持json格式
    • 缺点:但是支持的数据类型很少,有 字符串,列表,字典,整型,元祖(转为列表),bool值

    内置的方法:

    • dumps :序列化,将其他格式数据类型转成json格式的字符串
    • dump
    • loads :反序列化,将json格式的字符串转成其他格式的数据类型
    • load

    小技巧:加s的传入文件,不加s的不传文件

    import json
    ​
    d = {'name':'jason'}
    
    res = json.dumps(d)  # {"name":"jason"} json格式的字符串,必须是双引号
    
    print(res,type(res))  # <class 'str'>
    
    res1 = json.loads(res)  # {'name':'jason'}
    
    print(res1,type(res1))  # <class 'dict'>
    # 写入文件
    d = {"name":"jason"}
    
    with open('userinfo', 'w', encoding='utf-8') as f:
    
        # 先转字符串并自动写入文件
        json.dump(d,f)  # 若直接写json.dump(d)则报错
    
    
    # 读取文件    
    d = {"name":"jason"}
    
    with open('userinfo', 'r', encoding='utf-8') as f:
    
        res = json.load(f)
    
        print(res,type(res))  # {'name':'jason'}  <class 'dict'>
    如果进行多次反序列化操作后: 
    # 失败案例:
    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:
    
        res = json.load(f)  # 不能够多次反序列化
    
        res1 = json.load(f)
    
        print(res,type(res))
    
        print(res1,type(res1))
        
    # 直接报错
    反之:
    # 成功案例:    
    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))
    关于dumps方法的一些运用:       
    import json
    
    t = (1,2,3,4)
    
    print(json.dumps(t))  # [1,2,3,4]
    
    ​
    d1 = {'name':'朱质健'}
    
    print(json.dumps(d1))  # {"name": "u6731u8d28u5065"}
    
    
    d1 = {'name':'朱质健'}
    # 避免结果被转码
    print(json.dumps(d1,ensure_ascii=False))  # {"name": "朱质健"}

    pickle模块:


     

    优缺点:

    • 优点:只支持python语言
    • 缺点:但是支持python所有的数据类型

    注意点:用pickle操作文件时,文件的打开模式必须是b模式

    import pickle
    
    d = {'name':'jason'}
    
    res = pickle.dumps(d)  # 将对象直接转成二进制
    
    print(pickle.dumps(d))  # 二进制模式代码
    
    res1 = pickle.loads(res)
    
    print(pickle.loads(res),type(res))  # {'name':'jason'} <class 'dict'>

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


     

    sub :子  process :进程

     

    PS :终端内输入tasklist可查看进程详细信息的二进制码展示

    subprocess内置的方法:

    • stdout :正确命令返回的结果
    • stderr :错误命令返回的提示信息

    应用场景:远程运维/操控

     

    关于远程运维/操控:

    • 1.用户通过网络连接上了你的这台电脑
    • 2.用户输入相应的命令,基于网络发送给了你这台电脑上某个程序
    • 3.获取用户命令,里面subprocess执行该用户命令
    • 4.将执行结果再基于网络发送给用户

    最终就能实现,用户远程操控你这台电脑的操作!!!

    终端使用tasklist命令,并且使其转化为常用数据类型以展示:

    while True:
    
        cmd = input('cmd>>>:').strip()
    
        import subprocess
    
        obj = subprocess.Popen('tasklist', shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    
        print('正确命令返回的结果stdout',obj.stdout.read().decode('GBK'))
    
        print('错误命令返回的提示信息stderr',obj.stderr.read().decode('GBK'))
  • 相关阅读:
    1093 Count PAT's(25 分)
    1089 Insert or Merge(25 分)
    1088 Rational Arithmetic(20 分)
    1081 Rational Sum(20 分)
    1069 The Black Hole of Numbers(20 分)
    1059 Prime Factors(25 分)
    1050 String Subtraction (20)
    根据生日计算员工年龄
    动态获取当前日期和时间
    对计数结果进行4舍5入
  • 原文地址:https://www.cnblogs.com/zhukaijian/p/11209522.html
Copyright © 2011-2022 走看看