模块讲解---time模块,datetime模块,random模块,hashlib模块和hmac模块,typing模块,requests模块,re模块

目录

1. 包
2. time模块
??1. 优先掌握
2. 了解
3. datetime模块
??1. 优先掌握
4. random模块
??1. 优先掌握
??2. 了解
5. hashlib模块和hmac模块
6. typing模块
7. requests模块
8. re模块
??1. re模块的正则表达式的元字符和语法
??2. 贪婪模式和非贪婪模式
??3. 匹配邮箱实例
??4. re模块中的常用功能函数
??5. 修饰符 re.S
??6. 补充

目录

1. 包

  • 什么是包

    包就是模块

  • 包有什么用
    1. 当模块内的函数过多时,为了方便管理函数,把多个函数划分成多个模块,但同时不同改变原来的导入方式,把多个模块放入一个包(文件夹)内。
    2. 通过包,可以不改变用户的导入方式(就和装饰器不改变被装饰函数的调用方式同理),提高用户体验
    3. 未来导包就是导__init__
  • 在包的用法中主要注意的有两点
    1. 包是含有__init__.py的文件夹;导包就是导入__init__
    2. 包一定是被当做模块文件导入,模块文件的搜索路径以执行文件为准
  • 相对导入和绝对导入(只能在包中内部使用)

    相对导入:

    • .表示(同一文件夹下的)当前文件的目录
    • ..表示当前文件的父目录
    • ...表示当前文件的爷爷目录

    绝对导入:

    • 就是不用点表示目录,直接写名字

    2. time模块

  • time模块的作用

    提供了三种不同类型的时间(时间戳),三种不同类型的时间可以相互转换

  • 三种类型的时间
    • 格式化时间
    • 结构化时间
    • 时间戳

    ==他们是以结构化时间为中间介质,格式化时间和结构化时间可以互相转化;时间戳可以和结构化时间互相转化==

1. 优先掌握

import time
time.time() # 时间戳 (从计算机元年开始到现在的时间,以秒计算显示)

time.sleep(1)  # 让程序运行到这一步暂停1秒

2. 了解

import time

print(time.time())  # 时间戳形式

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

# 结构化时间
print(time.localtime())

# 结构化时间 --》 格式化时间
struct_time = time.localtime(3600*24*365)
print(time.strftime('%Y-%m-%d %X',struct_time))

# 格式化时间 --》 结构化时间
format_time = time.strftime('%Y-%m-%d %X')
print(time.strptime(format_time,'%Y-%m-%d %X'))

# 结构化时间 --》 时间戳
struct_time = time.localtime(3600*24*365)
print(time.mktime(struct_time))

# 时间戳 --》 结构化时间
time_stamp = time.time()
print(time.localtime(time_stamp))

3. datetime模块

  • datetime模块的作用

    可以实现时间的加减

1. 优先掌握

import datetime
# 获取当前时间
now = datetime.datetime.now()
print(now) # 2019-09-28 19:56:44.330734

# 默认3天 # 2019-10-01 19:56:44.330734
print(now + datetime.timedelta(3)) 

# 加3周 #2019-10-19 19:56:44.330734
print(now + datetime.timedelta(weeks=3))

# 加3小时 2019-09-28 22:56:44.330734
print(now + datetime.timedelta(hours=3))

# 减3小时 # 2019-09-28 16:56:44.330734
print(now - datetime.timedelta(hours=3))
print(now + datetime.timedelta(hours=-3))

# 1949-10-01 10:01:00
print(now.replace(year=1949, month=10, day=1, hour=10, minute=1, second=0, microsecond=0))

4. random模块

  • random模块的作用

    产生随机数

1. 优先掌握

import random

# 掌握

# 0-1
print(random.random())

# 产生一个[1-3]之间包括首尾的随机数
print(random.randint(1,3))

# 打乱
lt=[1,2,3]
random.shuffle(lt)
print(lt)

# 随机选择一个
print(random.choice(lt))

# 只随机一次  --> 梅森旋转算法
import time
# random.seed(time.time())
# random.seed(111111111111)
seed() 方法是改变随机数生成器的种子,也就是说,当使用seed()方法后,后面的产生的随机数就是一样的了。
seed()括号内的数不同,产生的随机数种子也不同
就是说 例如:
random.seed(1) 后面再产生的随机数都为 2
random.seed(2)后面再产生的随机数都为 3
print(random.random())

2. 了解

# 了解
print(random.sample([1,'a','c',2,3,4],2))

5. hashlib模块和hmac模块

  • hashlib模块的作用

    对字符加密

  • hmac模块的作用

    对字符加密,并且加上密钥,相当于用了两层加密。

  • hashlib模块的实例
import hashlib

# 叠加性
m = hashlib.md5()
# m.update(b'say')
# m.update(b'hello')  # 981fe96ed23ad8b9554cfeea38cd334a
m.update(b'hash123456')
print(m.hexdigest())  # 对于不同的字符而言,用不重复

# 981fe96ed23ad8b9554cfeea38cd334a

# 手机号/生日/性别/qq账号/以前的密码/   --》 挖矿(算法)

# 1 2 3 5 71113 111111111111111 - 1111111111111111111111 111111111111111111111111111111111111111111111111111

hash_pwd = '0562b36c3c5a3925dbe3c4d32a4f2ba2'

pwd_list = [
    'hash3714',
    'hash1313',
    'hash94139413',
    'hash123456',
    '123456hash',
    'h123ash',
]

for pwd in pwd_list:
    m = hashlib.md5()
    m.update(pwd.encode('utf8'))
    res = m.hexdigest()
    if res == hash_pwd:
        print(f'获取密码成功:{pwd}')
  • hamc模块的实例

    import hmac
    
    m = hmac.new(b'maerzi')
    m.update(b'hash123456')  # f82317e44545b0ab087109454814b5c4
    print(m.hexdigest())
    
    m = hmac.new(b'sdfjhjk2394879ul%$$Y#($&')
    m.update(b'hash123456')  # 2a70fd0f13cb49357f40d326a4e071a2
    print(m.hexdigest())
    
    pwd_list = [
        'hash3714',
        'hash1313',
        'hash94139413',
        'hash123456',
        '123456hash',
        'h123ash',
    ]

6. typing模块

  • typing模块的作用

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

  • 实例
    def func(x: int, lt: Iterable) -> list:
        return [1, 2, 3]
    
    func(10, '123123')

7. requests模块

  • request是模块的作用

    爬数据的模块,模拟浏览器对url发送请求,获取数据

  • 实例
    # url ——> 一个特定的网址 -》 永不重复
    import requests
    
    response = requests.get('https://ishuo.cn')
    data = response.text
    print(data)
    

re模块

1、\w \W

print(re.findall('\w','ab 12\+- _*&')) #\w 匹配字母 数字 及下划线
执行结果:['a', 'b', '1', '2', '_']
print(re.findall('\W','ab 12\+- _*&')) #\W 匹配非字母 数字 及下划线
执行结果:[' ', '\\', '+', '-', ' ', '*', '&']

2、\s  \S

print(re.findall('\s','ab 12\+- _*&')) #\s 匹配任意空白字符,等价于[\t\n\r\f]
执行结果:[' ', ' ']
print(re.findall('\S','ab 12\+- _*&')) #\S 匹配非空白字符
执行结果:['a', 'b', '1', '2', '\\', '+', '-', '_', '*', '&']

3、\d  \D

print(re.findall('\d','ab 12\+- _*&')) #\d 匹配任意数字,等价于[0-9]
执行结果:['1', '2']
print(re.findall('\D','ab 12\+- _*&')) #\D 匹配非数字
执行结果:['a', 'b', ' ', '\\', '+', '-', ' ', '_', '*', '&']

综合:

print(re.findall('\w_sb','egon alex_sb12332wxx_sb,lxx_sb'))
执行结果:['x_sb', 'x_sb', 'x_sb']

4、\A 基本上不用

print(re.findall('\Aalex','alex isalex sb'))#从头开始匹配只匹配第一个alex
执行结果:['alex']
print(re.findall('alex','alex isalex sb'))
执行结果:['alex', 'alex']

5、^

print(re.findall('^alex','alex is salexb'))#从头开始匹配,匹配到第一个则不往后匹配
执行结果:['alex']
print(re.findall('sb','alexsb is sbalexsb'))#从头开始匹配,匹配所有
执行结果:['sb', 'sb', 'sb']
print(re.findall('^sb','alexsb is sbalexsb'))#从头开始匹配,第一个没有则不往后面匹配
执行结果:[]

6、\Z  $

print(re.findall('sb\Z','alexsb is sbalexsb'))#从尾部开始匹配,匹配到则不往前匹配
执行结果:['sb']
print(re.findall('sb$','alexsb is sbalexsb'))#从尾部开始匹配,匹配到则不往前匹配
执行结果:['sb']

综合:

print(re.findall('^ebn$','ebn'))#从头开始找,正反找都是ebn,都可以匹配上
执行结果:['ebn']

7、\n  \t  (同理)

print(re.findall('\n','a\nc a\tc al\nc'))#匹配到\n
执行结果:['\n', '\n']
print(re.findall('a\nc','a\nc a\tc al\nc'))#匹配到['a\nc']
执行结果:['a\nc']

重复匹配:  .  ?    +  {m,n}  .  .*?

1、.  :代表除了换行符外的任意一个字符

print(re.findall('a.c','abc alc aAsc aaaaaac'))#匹配以a开头以c结尾.代表中间的任意一个字符
执行结果:['abc', 'alc', 'aac']
print(re.findall('a.c','abc alc aAc aaaaaa\nc'))#ac中间有换行符\n所以匹配不到a\nc
执行结果:['abc', 'alc', 'aAc']
print(re.findall('a.c','abc alc aAsc aaaaaa\nc',re.DOTALL))#.能匹配ac中间的所有一个字符,包括\n
执行结果:['abc', 'alc', 'a\nc']

2、?  :代表左边那一个字符重复0次或1次

print(re.findall('ab?','a ab abb abbb abbbb abbbbb albbbbb'))#从头匹配ab中,b是零个或一个
执行结果:['a', 'ab', 'ab', 'ab', 'ab', 'ab', 'a']

3、*  :代表左边那一个字符出现0次或无穷次

print(re.findall('ab*','a ab abb abbb abbbb abbbbb albbbbbbb'))#从头匹配ab中,b是零个或无穷个
执行结果:['a', 'ab', 'abb', 'abbb', 'abbbb', 'abbbbb', 'a']

4、+  :代表左边那一个字符出现至少一次或无穷次

print(re.findall('ab+','a ab abb abbb abbbb abbbbb albbbbbbb'))#从头匹配ab中,b是一个或无穷个
执行结果:['ab', 'abb', 'abbb', 'abbbb', 'abbbbb']

5、{m,n}  :代表左边那一个字符出现m次到n次

print(re.findall('ab?','a ab abb abbb abbbb abbbbb  albbbbbb'))
print(re.findall('ab{0,1}','a ab abb abbb abbbb abbbbb albbbbbb'))
执行结果:['a', 'ab', 'ab', 'ab', 'ab', 'ab', 'a'] , ['a', 'ab', 'ab', 'ab', 'ab', 'ab', 'a']
print(re.findall('ab*','a ab abb abbb abbbb abbbbb albbbbbbb'))
print(re.findall('ab{0,}','a ab abb abbb abbbb abbbbb albbbbbbb'))
执行结果:['a', 'ab', 'abb', 'abbb', 'abbbb', 'abbbbb', 'a'] , ['a', 'ab', 'abb', 'abbb', 'abbbb', 'abbbbb', 'a']
print(re.findall('ab+','a ab abb abbb abbbb abbbbb albbbbbbb'))
print(re.findall('ab{1,}','a ab abb abbb abbbb abbbbb albbbbbbb'))
执行结果:['ab', 'abb', 'abbb', 'abbbb', 'abbbbb'] , ['ab', 'abb', 'abbb', 'abbbb', 'abbbbb']
print(re.findall('ab{1,3}','a ab abb abbb abbbb abbbbb albbbbbbb'))
执行结果:['ab', 'abb', 'abbb', 'abbb', 'abbb']

6、.*  :匹配任意长度,任意的字符=====》贪婪匹配

print(re.findall('a.*c','ac a123c  aaaac a * 123) ()c asdfsdfkjdls'))#尽可能长的匹配
执行结果:['ac a123c  aaaac a * 123) ()c']

7、.*?  :非贪婪匹配

print(re.findall('a.*?c','a123c456c'))#尽可能短的匹配
执行结果:['a123c']

8、()  :分组

print(re.findall('(alex)_sb','alex_sb sfksdfksdalex_sb'))#在匹配到的情况下只留括号内的内容
执行结果:['alex', 'alex']

例子:非贪婪匹配到网址

print(re.findall('href="(.*?)"','<li><a id="blog_nav_sitehome" class="menu" href="https://www.cnblogs.com/happyfei/">博客园</a></li>'))
执行结果:['https://www.cnblogs.com/happyfei/']

9、[]  :匹配一个指定范围内的字符(这一字符来自于括号内定义的)

print(re.findall('a[0-9]c','a1c a+c a2c a9c a*c a11c a-c acc aAc '))#-号在[]内有特殊意义,如果要匹配带-号的,-号要放在最前面或最后面
执行结果:['a1c', 'a2c', 'a9c']
print(re.findall('a[-+*]c','a1c a+c a2c a9c a*c a11c a-c acc aAc '))
执行结果:['a+c', 'a*c', 'a-c']
print(re.findall('a[a-zA-Z]c','a1c a+c a2c a9c a*c a11c a-c acc aAc '))
执行结果:['acc', 'aAc']
print(re.findall('a[^a-zA-Z]c','a c a1c a+c a2c a9c a*c a11c a-c acc aAc '))#[]内的^代表取反的意思
执行结果:['a c', 'a1c', 'a+c', 'a2c', 'a9c', 'a*c', 'a-c']

例子:取出_sb

print(re.findall('[a-z]_sb','egon alex_sb12332wxx_sb,lxx_sb'))#[]匹配一个字符后面跟_sb
执行结果:['x_sb', 'x_sb', 'x_sb']
print(re.findall('[a-z]+_sb','egon alex_sb12332wxxxxx_sb,lxx_sb'))#[]+匹配多个字符后面跟_sb
执行结果:['alex_sb', 'wxxxxx_sb', 'lxx_sb']
print(re.findall('([a-z]+)_sb','egon alex_sb12332wxxxxx_sb,lxx_sb'))#只取到_sb的人名
执行结果:['alex', 'wxxxxx', 'lxx']

10、|  :代表或者

print(re.findall('compan(ies|y)','Too many companies have gone bankrupt, and the next none is my company'))#取出公司的英文单词
执行结果:['ies', 'y']

注:(?:代表取匹配成功的所有内容,而不仅仅只是括号内的内容)

print(re.findall('compan(?:ies|y)','Too many companies have gone bankrupt, and the next none is my company'))
执行结果:['companies', 'company']
print(re.findall('alex|sb','alex sb ssdfsdf  alex sb egon'))
执行结果:['alex', 'sb', 'alex', 'sb']

11、re模块的其他用法

 1 print(re.findall('alex|sb','123123 alex sb sdlfjlsdkegon alex sb egon'))
 2 print(re.search('alex|sb','123123 alex sb sdlfjlsdkegon alex sb egon').group())
 3 #执行结果:['alex', 'sb', 'alex', 'sb'] , alex
 4
 5
 6 print(re.search('^alex','alex sb sdlfjlsdkegon alex sb egon').group())#表示从头开始匹配
 7 print(re.match('alex','alex sb sdlfjlsdkegon alex sb egon').group())#表示从头开始匹配
 8 #执行结果:alex , alex
 9
10
11 info='a:b:c:d'
12 print(info.split(':'))
13 print(re.split(':',info))
14 #执行结果:['a', 'b', 'c', 'd'] , ['a', 'b', 'c', 'd']
15
16 info='a :c\d/e'
17 print(re.split('[ :\\\/]',info))
18 #执行结果:['a', '', 'c', 'd', 'e']
19
20 #需求:xxx与Sb调换
21 print(re.sub('(xxx)(.*?)(SB)',r'\3\2\1',r'xxx is SB'))
22 #执行结果:SB is xxx
23
24 print(re.sub('([a-zA-Z]+)([^a-zA-Z]+)([a-zA-Z]+)([^a-zA-Z]+)([a-zA-Z]+)',r'\5\2\3\4\1',r'xxx123+ is SB'))
25 #执行结果:SB123+ is xxx
26
27 pattern=re.compile('alex')#把常用的正则表达式式存起来,以后直接用
28 print(pattern.findall('alex is alex sdjflk alexalex'))
29 #执行结果:['alex', 'alex', 'alex', 'alex']

原文地址:https://www.cnblogs.com/whkzm/p/11605195.html

时间: 2024-08-26 12:14:06

模块讲解---time模块,datetime模块,random模块,hashlib模块和hmac模块,typing模块,requests模块,re模块的相关文章

Python常用模块之json、pickle、random、hashlib、collections

1.json和pickle json用于字符串和Python数据类型间进行转换pickle用于python特有的类型和python的数据类型间进行转换json和pickle均提供了四种方法dumps,dump,loads,load ##json dumps() ##转换成字符串 loads() ##将json编码的字符串再转换为python的数据结构 dump() ##转换成字符串并存存储到文件中 load() ##从数据文件中读取数据,并将json编码的字符串转换为python的数据结构 >>

Python 常用模块之time&amp;datetime 和random

本节大纲: 模块介绍 time &datetime模块 random 一.模块介绍: 模块,用一砣代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合.而对于一个复杂的功能来,可能需要多个函数才能完成 (函数又可以在不同的.py文件中),n个 .py 文件组成的代码集合就称为模块. 如:os 是系统相关的模块:file是文件操作相关的模块 模块分为三种: ①自定义模块 ②内置标准模块(又称标准库) ③开源

6 - 常用模块(os,sys,time&amp;datetime,random,json&amp;picle,shelve,hashlib)

导入模块 想使用 Python 源文件,只需在另一个源文件里执行 import 语句 import module1[, module2[,... moduleN] from语句让你从模块中导入一个指定的部分到当前命名空间中 from modname import name1[, name2[, ... nameN]] 内置的函数 dir() 可以找到模块内定义的所有名称.以一个字符串列表的形式返回 >>> import sys >>> dir(sys) ['__disp

python模块time,datetime,random,os,sys

一:内建模块 1. time和datetime(http://www.jb51.net/article/49326.htm) 在Python中,通常有这几种方式来表示时间:1)时间戳 2)格式化的时间字符串 3)元组(struct_time)共九个元素.由于Python的time模块实现主要调用C库,所以各个平台可能有所不同. UTC(Coordinated Universal Time,世界协调时)亦即格林威治天文时间,世界标准时间.在中国为UTC+8.DST(Daylight Saving

自定义模块,time,datetime以及random

自定义模块,time,datetime以及random 1.自定义模块 自定义一个模块 import #导入 (拿工具箱) 模块分类 1.内置模块(标准库) --python解释器自带的.py文件(模块) 2.第三方模块(大神写的) --需要额外下载的(www.pypi.org) 3.自定义模块(自己写的) --不需要额外下载 分模块的好处: 1.避免写重复代码 2.可以多次利用 3.拿来主义(拿来就用) 导入发生的事情: 1.在当前的名称空间开辟一个新的空间 2.将模块中所有的模块执行 3.通

Python之日期与时间处理模块(date和datetime)

本节内容 前言 相关术语的解释 时间的表现形式 time模块 datetime模块 时间格式码 总结 前言 在开发工作中,我们经常需要用到日期与时间,如: 作为日志信息的内容输出 计算某个功能的执行时间 用日期命名一个日志文件的名称 记录或展示某文章的发布或修改时间 其他 Python中提供了多个用于对日期和时间进行操作的内置模块:time模块.datetime模块和calendar模块.其中time模块是通过调用C库实现的,所以有些方法在某些平台上可能无法调用,但是其提供的大部分接口与C标准库

那些年被我坑过的Python——道阻且长(第五章实用模块讲解)

random模块 我的随机验证吗程序: 首先保证了字母和数字出现的概率是50% VS 50%,其次是可以订制输出多少位 1 def Captcha(size): 2 Captcha_list = [] 3 for i in range(size): 4 rand_num = random.randint(1, 2) 5 if rand_num == 1: 6 Captcha_list.append(chr(random.randint(65, 90))) 7 elif rand_num == 2

python 3 之日期与时间处理模块(date和datetime)

前言相关术语的解释时间的表现形式time模块datetime模块时间格式码总结前言 在开发工作中,我们经常需要用到日期与时间,如: 作为日志信息的内容输出计算某个功能的执行时间用日期命名一个日志文件的名称记录或展示某文章的发布或修改时间其他Python中提供了多个用于对日期和时间进行操作的内置模块:time模块.datetime模块和calendar模块.其中time模块是通过调用C库实现的,所以有些方法在某些平台上可能无法调用,但是其提供的大部分接口与C标准库time.h基本一致.time模块

json、pickle\shelve模块讲解

json.pickle模块讲解 见我前面的文章:http://www.cnblogs.com/itfat/p/7456054.html shelve模块讲解(超级好用~!) json和pickle的模块只允许dump和load一次,而shelve可以支持多次. shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式 执行这段代码以后会生成三个文件: 然后我们再把它读取出来:

很全很全的 JavaScript 模块讲解

模块通常是指编程语言所提供的代码组织机制,利用此机制可将程序拆解为独立且通用的代码单元.所谓模块化主要是解决代码分割.作用域隔离.模块之间的依赖管理以及发布到生产环境时的自动化打包与处理等多个方面. 模块的优点 可维护性. 因为模块是独立的,一个设计良好的模块会让外面的代码对自己的依赖越少越好,这样自己就可以独立去更新和改进. 命名空间. 在 JavaScript 里面,如果一个变量在最顶级的函数之外声明,它就直接变成全局可用.因此,常常不小心出现命名冲突的情况.使用模块化开发来封装变量,可以避