常用内置模块(2) 一、time模块 二、datetime模块 三、random模块 四、hashlib模块 五、hmac模块 六、typing模块 七、requests模块 八、re模块

1、时间戳

import time
res = time.time()  # 时间戳形式
print(res)

# 1569667754.9504838

2、格式化时间

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

# 2019-09-28 18:49:14

3、结构化时间

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

# time.struct_time(tm_year=2019, tm_mon=9, tm_mday=28, tm_hour=18, tm_min=49, tm_sec=14, tm_wday=5, tm_yday=271, tm_isdst=0)

4、不同格式的时间互相转换

4.1 结构化时间 —> 格式化时间

struct_time = time.localtime(3600*24*365)
print(time.strftime('%Y-%m-%d %X',struct_time))

# 2019-09-28 18:52:18

4.2 格式化时间 —> 结构化时间

format_time = time.strftime('%Y-%m-%d %X')
print(time.strptime(format_time,'%Y-%m-%d %X'))

# time.struct_time(tm_year=2019, tm_mon=9, tm_mday=28, tm_hour=18, tm_min=52, tm_sec=18, tm_wday=5, tm_yday=271, tm_isdst=-1)

4.3 结构化时间 —> 时间戳

struct_time = time.localtime(3600*24*365)  # 括号中加时间是从计算机元年1970年1月1日 0:0:0 开始计算的
print(time.mktime(struct_time))

# 31536000.0

4.4 时间戳 —> 结构化时间

time_stamp = time.time()
print(time.localtime(time_stamp))

# time.struct_time(tm_year=2019, tm_mon=9, tm_mday=28, tm_hour=18, tm_min=52, tm_sec=18, tm_wday=5, tm_yday=271, tm_isdst=0)

二、datetime模块

用来进行时间的加减计算

import datetime

now = datetime.datetime.now()
print(now)

# 默认3天
print(now + datetime.timedelta(3))
# 加3周
print(now + datetime.timedelta(weeks=3))
# 加3小时
print(now + datetime.timedelta(hours=3))
# 减3小时
print(now - datetime.timedelta(hours=3))
print(now + datetime.timedelta(hours=-3))
# 替换时间
print(now.replace(year=1949, month=10, day=1, hour=10, minute=1, second=0, microsecond=0))


'''
2019-09-28 18:56:48.240483
2019-10-01 18:56:48.240483
2019-10-19 18:56:48.240483
2019-09-28 21:56:48.240483
2019-09-28 15:56:48.240483
2019-09-28 15:56:48.240483
1949-10-01 10:01:00
'''

三、random模块

随机数模块

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)  # 以具体的数计算,只计算一次,之后每次都一样
print(random.random())

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


'''
0.6264256562221452
2
[3, 2, 1]
1
0.08023345502018553
[2, 1]
'''

四、hashlib模块

对字符加密的模块

import hashlib

m = hashlib.md5()
m.update(b'hello') # 等同于m.update('hello'.encode('utf-8'))
print(m.hexdigest())

# 5d41402abc4b2a76b9719d911017c592
# Unicode-objects must be encoded before hashing

五、hmac模块

对字符加密,且可以使用密钥

import hmac

m = hmac.new(b'maerzi')  # 加密钥
m.update(b'hash123456')  
print(m.hexdigest())  # f82317e44545b0ab087109454814b5c4

六、typing模块

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

from typing import Iterable  # 迭代器对象

lt = [1, 2, 3, 4]  # 只是可迭代对象
print(type(lt) is list)  # True
print(lt == Iterable)  # False

七、requests模块

模拟浏览器对URL发送请求,拿到数据,通常用于网络爬虫

import requests

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

八、re模块

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

1、re模块的基本语法

import re  # 第一步,要引入re模块

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

2、re模块的特殊字符

^:以...开头

s = 'abcdabc'
res = re.findall('^ab', s)
print(res)
res = re.findall('^bc', s)
print(res)

# ['ab']
# []

$: 以..结尾

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

# ['bc']

. : 任意字符

s = 'abc红abc'
res = re.findall('abc.', s)
print(res)

# ['abc红']

d: 数字

s = 'skld2342ljk'
res = re.findall('d', s)
print(res)

# ['2', '3', '4', '2']

w: 非空,数字字母下划线(不包含特殊字符)

s = 'skld_23 42ljk'
res = re.findall('w', s)
print(res)

# ['s', 'k', 'l', 'd', '_', '2', '3', '4', '2', 'l', 'j', 'k']

s:空,空格/ /

s = 'skld_23 42ljk'
res = re.findall('s', s)
print(res)

# [' ']

D: 非数字

s = 'skld2342ljk'
res = re.findall('D', s)
print(res)

# ['s', 'k', 'l', 'd', 'l', 'j', 'k']

W: 空

s = 'skld_23 42ljk'
res = re.findall('W', s)
print(res)

# [' ']

S:非空

s = 'skld_23 42ljk'
res = re.findall('S', s)
print(res)

# ['s', 'k', 'l', 'd', '_', '2', '3', '4', '2', 'l', 'j', 'k']

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

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

# ['abcddddd', 'abcd']

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

s = 'abcddddd abcd abc'
print(re.findall('abcd?', s))

# ['abcd', 'abcd', 'abc']

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

s = 'abcdddddddddddddddddd abcd abc'
print(re.findall('abcd*', s))

# ['abcdddddddddddddddddd', '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']

{m}:前面的字符m个

s = 'abccabc abccc'
print(re.findall('abc{2}', s))

# ['abcc', 'abcc']

{1,2}:前面的字符1或2个

s = 'abccabc abccc'
print(re.findall('abc{1,2}', s))

# ['abcc', 'abc', 'abcc']

3、贪婪模式与非贪婪模式

3.1 贪婪模式

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

s = 'abcdefgbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbg'
print(re.findall('a.*g', s))  # 第一个a到最后一个g

# 我全都要
# ['abcdefgbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbg']

3.2 非贪婪模式

# .(任意字符)*(0-无穷个)?(让他进入非贪婪模式)
s = 'abcdefgbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbg'
print(re.findall('a.*?g', s))  # 最后一个a到第一个g

# 够了
# ['abcdefg']

4、特殊构造

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

# ['a', 'a']
# ['a', 'a', 'a', 'a', 'a', 'a']

5、compile

s = '#@#@#@nickchen121@163.com$$$$////nick@qq.com$$#$#$[]]2287273393@162.com@$2423423lksdlfj#'

email_pattern = re.compile('w+@w+.com')
# phone_patter = re.compile('d{11}')
print(re.findall(email_pattern, s))
s = 'abcd abcddd abc'
print(re.findall('abcd*', s))

# ['nickchen121@163.com', 'nick@qq.com', '2287273393@162.com']
# ['abcd', 'abcddd', 'abc']

6、match和search

# match:  从开头找一个,找得到就不找了 ;找不到报错 --》
s = 'abcd abcddd abc'
res = re.match('abcd*', s)
print(res.group())

# search: 从字符串找一个,就不找了
s = 'ab abcddd abc'
res = re.search('abcd*', s)
print(res.group())

# abcd
# abcddd

7、split

s = 'ab23423abcddd234234abcasdfjlasjdk234l23lk4j2kl34kl25k3j2kl3j5lkj'
print(re.split('d+', s))

# ['ab', 'abcddd', 'abcasdfjlasjdk', 'l', 'lk', 'j', 'kl', 'kl', 'k', 'j', 'kl', 'j', 'lkj']

8、sub (相当于replace)

s = 'ab23423abcddd234234abcasdfjlasjdk234l23lk4j2kl34kl25k3j2kl3j5lkj'
print(re.sub('d+', ' ', s))

# ab abcddd abcasdfjlasjdk l lk j kl kl k j kl j lkj

9、subn --> sub + 替换了多少次

s = 'ab23423abcddd234234abcasdfjlasjdk234l23lk4j2kl34kl25k3j2kl3j5lkj'
print(re.subn('d+', ' ', s))

# ('ab abcddd abcasdfjlasjdk l lk j kl kl k j kl j lkj', 12)

10、补充(非常有用)

10.1 修饰符 --> 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']

# ['abc*abc']
# ['abc
abc', 'abc*abc']

10.2 分组 --> 只要括号里的(*****)

s = 'abc abcd abcdd'
print(re.findall('a(.)c(d)', s))

# [('b', 'd'), ('b', 'd')]

10.3 有名分组(了解)

s = 'abc abcd abcdd'
print(re.search('a(?P<name>.)c(?P<name2>d)', s).groupdict())

# {'name': 'b', 'name2': 'd'}

10.4 超高级用法

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