• 模块 time,datetime,random,typing,hashlib,requests,re


    什么是包

    包是模块的一种形式,就是含有.py文件的文件夹

    为什么要包

    刚开始模块只有几个功能,未来模块扩展功能,模块名和用法应该最好不要去修改,但这是对于用户来说是方便了,对于开发者来说,模块管理起来很麻烦,所以就用包来扩展模块的功能。

    1. 包的介绍

    1. 本质就是模块,实际上就是一个含有__init__.py文件的文件夹
    2. 导包就是导入__init__.py文件
    3. 包一定是被当作模块文件导入,模块文件的搜索路径以执行文件的路径为准

    2. 绝对导入和相对导入

    只能在包中使用

    - 绝对导入

    from 包名.模块名 import 方法名

    - 相对导入

    • .代表当前被导入文件所在的文件夹
    • ..代表当前被导入文件所在的文件夹的上一级
    • ...代表当前被导入文件所在的文件夹的上一级的上一级

    time模块

    时间戳

    import time
    
    print(time.time())   # 从1970年1月1日00:00:00开始计算到现在的秒数
    

    格式化时间

    import time 
    print(time.strftime('%Y-%m-%d %H:%M:%S'))  # 2019-09-28 17:15:47
    
    print(time.strftime('%Y-%m-%d %X'))   # 2019-09-28 17:16:50
    

    结构化时间

    import time
    print(time.localtime())   # time.struct_time(tm_year=2019, tm_mon=9, tm_mday=28, tm_hour=17, tm_min=18, tm_sec=11, tm_wday=5, tm_yday=271, tm_isdst=0)
    
    # 结构化基础时间
    import time
    print(time.localtime(0))   # time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=8, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
    

    sleep

    import time 
    
    start = time.time()
    time.sleep(2)
    end = time.time()
    print(f'暂停了{end - start}秒')  # 暂停了2.000108003616333秒
    

    datetime模块

    import datetime
    
    # 输出当前时间
    print(datetime.datetime.now())
    # 2019-09-28 17:25:24.551237
    
    
    # 加时间
    now = datetime.datetime.now()
    print(now + datetime.timedelta(days=3))
    # 2019-10-01 17:28:24.710093
    
    
    print(now.replace(year=1940))
    # 1940-09-28 17:29:45.066855
    

    random模块

    import random
    
    # 0-1随机数
    print(random.random())
    
    
    # 1-100随机整数
    print(random.randint(1,100))
    
    # 1-3之间随机整数
    print(random.randrange(1, 3))
    
    # 打乱lt的顺序
    lt = [1,2,4,60]
    random.shuffle(lt)   # [4, 1, 60, 2]
    print(lt)
    
    # 随机选择lt中一个元素
    print(random.choice(lt))
    
    # random.seed
    import random
    
    random.seed(4)   # 给一个随机数种子
    print(random.random())   # 只第一次随机生成,之后生成的数字就一样了
    print(random.random())
    
    # 如果不自定义种子,则种子按照当前的时间来
    

    typing模块

    与函数联用,控制函数参数的数据类型,提供了基础数据类型之外的数据类型

    from typing import Iterable
    
    def func(x:int, lt:list) -> list:
        return [1,2,3]
    
    func(10,[12,3])
    

    typing常用类型

    • int、long、float: 整型、长整形、浮点型
    • bool、str: 布尔型、字符串类型
    • List、 Tuple、 Dict、 Set:列表、元组、字典、集合
    • Iterable、Iterator:可迭代类型、迭代器类型
    • Generator:生成器类型

    hashlib模块

    hash是什么

    hash是一种算法(Python3.版本里使用hashlib模块代替了md5模块和sha模块,主要提供 SHA1、SHA224、SHA256、SHA384、SHA512、MD5 算法),该算法接受传入的内容,经过运算得到一串hash值。

    import hashlib
    
    m = hashlib.md5()
    m.update(b'sayhello')   # 981fe96ed23ad8b9554cfeea38cd334a
    print(m.hexdigest())   # 对于不同的字符而言,永不重复
    

    撞库破解hash算法

    pwd_list = [
        'hash3714',
        'hash1313',
        'hash94139413',
        'hash123456',
        '123456hash',
        'h123ash',
    ]
    
    hash_pwd = '0562b36c3c5a3925dbe3c4d32a4f2ba2'
    
    for pwd in pwd_list:
        m = hashlib.md5()
        m.update(pwd.encode('utf-8'))
        res = m.hexdigest()
        if res in hash_pwd:
            print(f'获取密码成功:{pwd}')  # 获取密码成功:hash123456
    

    hmac模块

    密钥 加盐

    import hmac
    
    m = hmac.new(b'haha')
    m.update(b'hash123456')
    print(m.hexdigest())    # 24bb8daab11e526fc9b8178e51bc2ae7
    
    
    m = m = hmac.new(b'sadness')
    m.update(b'hash123456')
    print(m.hexdigest())   # df405ffd019d6d3cd9a190fcab33aca5
    

    requests模块

    可以用来爬取数据,模拟浏览器对url发送请求,拿到数据

    import requests
    
    response = requests.get('https://www.baidu.com')
    print(response.text)
    

    re模块

    去字符串找符合某种特点的字符串

    re模块的基本使用:

    import re  # 第一步,要引入re模块
    a = re.findall("匹配规则", "这个字符串是否有匹配规则的字符")  # 第二步,调用模块函数
    print(a)  # 以列表形式返回匹配到的字符串
    

    ^字符

    以……开头

    s = 'abcdabc'
    
    res = re.findall('^abc',s)  
    print(res)                  # ['abc']
    res = re.findall('^bc',s)
    print(res)                  # []
    

    $ 字符

    以……结尾

    s = 'abcdabc'
    
    res = re.findall('bc$',s)
    print(res)             # ['bc']
    

    . : 任意字符

    s = 'abc是dabc'
    
    res = re.findall('abc.',s)
    print(res)   # ['abc是']
    

    d:数字

    s = 'asdhg213214h4c'
    
    res = re.findall('d',s)
    print(res)   # ['2', '1', '3', '2', '1', '4', '4']
    

    D: 非数字

    s = 'asdhg2132 -14h4c'
    
    res = re.findall('D',s)
    print(res)   # ['a', 's', 'd', 'h', 'g', ' ', '-', 'h', 'c']
    

    w: 非空, 数字、字母、下划线

    s = 'asdhg213214h4c'
    
    res = re.findall('w',s)
    print(res)   # ['a', 's', 'd', 'h', 'g', '2', '1', '3', '2', '1', '4', 'h', '4', 'c']
    

    W: 空,除了数字、字母、下划线外

    s = 'as;g:21?32    -14h4c
    '
    
    res = re.findall('W',s)
    print(res)  # [';', ':', '?', ' ', ' ', ' ', ' ', '-', '
    ']
    

    s: 空

    s = 'asdhg2132 14h4c'
    
    res = re.findall('s',s)
    print(res)    # [' ']
    

    S : 不空

    s = 'asdhg2132    -14h4c
    '
    
    res = re.findall('S',s)
    print(res)  # ['a', 's', 'd', 'h', 'g', '2', '1', '3', '2', '-', '1', '4', 'h', '4', 'c']
    

    +: 前面的1个字符至少1个

    s = 'abcdddd abcd abc ab'
    print(re.findall('abc+', s))
    

    ?: 前面的1个字符0-1个

    s = 'abcdddd abcd abc ab a'
    print(re.findall('abc?', s))  # ['abc', 'abc', 'abc', 'ab']
    

    *: 前面的1个字符至少0个

    s = 'abcdddd abcd abc ab a'
    print(re.findall('abcd*', s))   # ['abcdddd', 'abcd', 'abc']
    

    []: 中括号内的都可以

    s = 'abc bbc cbc dbc'
    print(re.findall('[abc]bc', s))  # ['abc', 'bbc', 'cbc']
    

    [^] : 中括号的都不可以

    s = 'abc bbc cbc dbc'
    print(re.findall('[^abc]bc', s))  # ['dbc']
    

    | : 或

    s = 'abc bbc dbc'
    print(re.findall('abc|bbc', s))  # ['abc', 'bbc']
    

    {2} : 前面的字符2个

    s = 'abcccab abcc'
    print(re.findall('abc{2}', s))   # ['abcc', 'abcc'] 
    print(re.findall('abc{0,2}', s))  # ['abcc', 'ab', 'abcc']
    

    贪婪模式

    (任意字符) * (0-无穷个)

    s = 'abcdefgaaaaaaaaaaag'
    print(re.findall('a.*g',s))
    # ['abcdefgaaaaaaaaaaag']
    

    非贪婪模式

    (任意字符) * (0-无穷个) ?

    s = 'abcdefgbbbbbbbg'
    print(re.findall('a.*?g',s))   # ['abcdefg']
    

    了解:特殊构造

    # a(?=d) :a后面是数字,但是不要数字,不消耗字符串内容
    s = 'a123 aaaa a234 abc'
    print(re.findall('a(?=d)', s))  #['a', 'a']
    
    print(re.findall('a(?=w)', s))  #['a', 'a', 'a', 'a', 'a', 'a']
    

    compile

    # 早期,re.findall不能传模式,只能用compile
    s = '#@#@#@nickchen121@163.com$$$$////nick@qq.com$$#$#$[]]2287273393@162.com@$2423423lksdlfj#'
    email_pattern = re.compile('w+@w+.com')
    phone_patter = re.compile('d{13}')
    print(re.findall(email_pattern, s))
    

    match : 从开头找一个,找的到就不找了,找不到就报错

    s = 'abcd abcddd abc'
    res = re.match('abcd*', s)
    print(res.group())  # abcd
    

    search: 从字符串找一个,就不找了

    s = 'abcd abcddd abc'
    res = re.search('abcd*', s)
    print(res.group())  # abcd
    

    split 切分

    s = 'adad213114242wjdnadjia1241423daj'
    print(re.split('d+', s))  # ['adad', 'wjdnadjia', 'daj']
    

    sub 替换

    s = 'adad213114242wjdnadjia1241423daj'
    print(re.sub('d+', '  ', s))  # adad  wjdnadjia  daj
    

    subn 替换,比sub多了 替换了多少次

    s = 'adad213114242wjdnadjia1241423daj'
    print(re.subn('d+', '  ', s))   # ('adad  wjdnadjia  daj', 2)
    

    补充: re.S

    s = '''abc
    abcabc*abc
    '''
    
    print(re.findall('abc.abc',s ))  # ['abc*abc']   原本.不匹配换行
    
    print(re.findall('abc.abc',s ,re.S))  # ['abc
    abc', 'abc*abc']
    

    分组: 只要括号里的

    s = 'abc abcd abcddd'
    print(re.findall('a(.)c(d)', s))  # [('b', 'd'), ('b', 'd')]
    

    有名分组

    s = 'abc abcd abcddd'
    print(re.search('a(?P<name1>.)c(?P<name2>d)', s).groupdict()) # {'name1': 'b', 'name2': 'd'}
    

    超高级用法

    s = 'abc123abc123'  # c123a
    print(re.sub('c(d+)a', ' ', s))
    print(re.sub('c(?P<name1>d+)a', ' g<name1> ', s))  # g<name1>这个东西不能替换掉
    
    # ab bc123
    # ab 123 bc123
    
  • 相关阅读:
    asp.net core过滤器记录响应对象
    ef core实现无感知软删除
    Egret资源跨域问题
    ASP.Net Core中使用jquery-ajax-unobtrusive替换Ajax.BeginForm
    把.Net开发环境迁移到Linux上去
    Mysql8.0升级后,Navicat连接报错caching_sha2_password 问题
    改MySQL的编码方式,解决jdbc MySQL中文乱码问题
    怡红公子专属网址导航
    html以前没有学到的标签
    有哪些质量上乘的程序员必关注的网站或论坛
  • 原文地址:https://www.cnblogs.com/setcreed/p/11628032.html
Copyright © 2020-2023  润新知