模块讲解---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 匹配任意空白字符,等价于[	

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、  $

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

综合:

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

7、      (同理)

print(re.findall('
','a
c a	c al
c'))#匹配到

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

重复匹配:  .  ?    +  {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
c'))#ac中间有换行符
所以匹配不到a
c
执行结果:['abc', 'alc', 'aAc']
print(re.findall('a.c','abc alc aAsc aaaaaa
c',re.DOTALL))#.能匹配ac中间的所有一个字符,包括

执行结果:['abc', 'alc', 'a
c']

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 :cd/e'
17 print(re.split('[ :\/]',info))
18 #执行结果:['a', '', 'c', 'd', 'e']
19 
20 #需求:xxx与Sb调换
21 print(re.sub('(xxx)(.*?)(SB)',r'321',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'52341',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