Python内置模块之re


一.取消转义

在原生的正则表达式中取消转义推荐使用\(每个\只能取消一个字符的转义)

在Python中取消转义推荐使用r'\n\a\t'(也可以使用\)

二.Python内置模块之re模块

①findall,search,match用法

 1 '''基本操作方法'''
 2 import re
 3 re.findall('正则表达式',  '待匹配的文本')  # 根据正则匹配除所有符合条件的数据
 4 res = re.findall('a', 'eva jason jack')
 5 print(res)  # ['a', 'a', 'a']
 6 res = re.findall('b', 'eva,jason,jack')
 7 print(res)  # 如果正则表达式不存在的话就会直接生成一个空列表
 8 
 9 re.search('正则表达式', '待匹配的文本') # 根据正则匹配到一个符合条件的就结束
10 res = re.search('a', 'eva jason jack')
11 print(res.group())  #如果遇到符合条件的就会直接结束,不存在的话就会直接返回none 并且使用group就会直接报错
12 
13 re.match('正则表达式',  '待匹配的文本')
14 res = re.match('a', 'abcd')  #根据正则从头开始匹配(文本内容必须在开头匹配上)
15 print(res)  # 结果对象
16 print(res.group())  # 如果没有符合条件的数据 那么match返回none 并且使用group会直接报错

②split,replace,subn,compile,finditer用法

 1 res = re.split('[ab]', 'abcd')
 2 print(res)  # ['', '', 'cd'] 先按照'a'分割得到''和'bcd',再对'bcd'和"abcd'分割
 3 
 4 # 返回元组,并提示换了几处
 5 res = re.subn(r'\d', 'H', 'eva3jason4yuan4', 1)
 6 print(res)
 7 
 8 # 给模块取一个别名compile
 9 regexp_odj = re.compile(r'\d+')
10 res = regexp_odj.search('abcdefghik')
11 res1 = regexp_odj.findall('alkjnjs12')
12 res2 = regexp_odj.match('acbhnik')
13 
14 # finditer
15 res = re.finditer(r'\d+', 'ashdklah21h23kj12jk3klj112312121kl131')
16 print([i.group() for i in res])
17 # ['21', '23', '12', '3', '112312121', '131']
18 
19 # 有名分组和无名分组
20 # findall遇到分组时会优先展示
21 # 无名分组
22 res = re.findall("^[1-9]\d{14}(\d{2}[0-9x])?$",'110105199812067023')
23 print(res)  # ['023']
24 # 取消分组优先显示 无名分组
25 res1 = re.findall("^[1-9](?:\d{14})(?:\d{2}[0-9x])?$",'110105199812067023')
26 print(res1)
27 # 有名分组
28 res = re.search('^[1-9](?P\d{14})(?P\d{2}[0-9x])?$','110105199812067023')
29 print(res.group())

这里举一个实战的案例

 1 import re
 2 
 3 # 读取带匹配的数据
 4 with open(r'/Users/mac/PycharmProjects/11月25日/网页.txt', 'r', encoding='utf8') as f:
 5     data = f.read()
 6 # 利用正则匹配数据
 7 # 获取分公司的名称
 8 title_list = re.findall('

(.*?)

', data) 9 # 获取分公司地址 10 adress_list = re.findall("

(.*?)

", data) 11 # 获取公司邮箱 12 email_list = re.findall("

(.*?)

", data) 13 # 获取公司电话 14 phone_number = re.findall("

(.*?)

", data) 15 res = zip(title_list, adress_list, email_list, phone_number) 16 # print(list(res)) 17 for data_tuple in res: 18 print(""" 19 公司名称:%s 20 公司地址:%s 21 公司邮箱:%s 22 公司电话:%s 23 """ % (data_tuple[0],data_tuple[1],data_tuple[2],data_tuple[3]) 24 )

三.collections模块

①namedtuple具名元组

 1 # namedtuple(具名元组)
 2 # 语法格式
 3 from collections import namedtuple
 4 """
 5 namedtuple('名称',[名字1,名字2,名字3])
 6 nameedtuple('名称','名字1 名字2 ...')
 7 """ 
 8 pp = namedtuple('坐标', ['x', 'y'])
 9 res = pp(11, 22)
10 print(res)  # 坐标(x=11, y=22)
11 jj = namedtuple('年龄', ['张三', '李四', '王五'])
12 res1 = jj(18, 19, 10)
13 print(res1)
14 print(res1.王五)  # 10

②列队模块

 1 # 队列模块
 2 import queue  # 内置队列模块
 3 
 4 # 初始化队列
 5 q = queue.Queue()
 6 
 7 # 在队列中添加元素
 8 q.put('第一个')
 9 q.put('d第二个')
10 
11 # 在列队中取出元素
12 print(q.get())
13 print(q.get())
14 """值去没了就会原地等待"""
15 
16 # 双端队列
17 from collections import deque
18 
19 q = deque([11, 12, 13])
20 q.append(44)  # 从右添加
21 print(res)  # 从从右边开始取值取值
22 print(q.pop())  # 从右边开始取值

③有序字典

 1 # 有序字典
 2 normal_dict = ([('name', 'jason'), ('age', 18), ('sex', '')])
 3 print(normal_dict)
 4 '''
 5 使用字典时,key是无序的。在做字典迭代时,我们无法确定key的顺序
 6 如果要保持key的顺序,可以使用OrderedDict处理
 7 '''
 8 from collections import OrderedDict
 9 
10 od = OrderedDict([('name', 'jason'), ('age', 18), ('sex', '')])
11 print(od)

④默认值字典

 1 # 默认值字典
 2 
 3 from collections import defaultdict
 4 
 5 value1 = [11, 12, 33, 44, 55, 66, 77]
 6 my_dict = defaultdict(list)
 7 for value in value1:
 8     if value > 60:
 9         my_dict['k1'].append(value)
10     else:
11         my_dict['k2'].append(value)
12 print(my_dict)

⑤计数器

1 # 计时器
2 res = 'abcddfbsbdb'
3 from collections import Counter
4 ret = Counter
5 print(ret)

⑥计时器

1 # 计时器
2 res = 'abcddfbsbdb'
3 from collections import Counter
4 ret = Counter
5 print(ret)

四.time模块

模块的三种表现形式

1.时间戳(秒数)

2.结构化时间

3.格式化时间(一般是给人看的)

1 # time.time()   # 获取时间戳
2 # time.sleep()  # 原地阻塞指定秒数
3 import time
4 # 格式化时间
5 print(time.strftime('%y-%m-%d %H:%M:%S'))
6 """更多时间相关符号 保存到容易查找的位置即可"""

五.datetime模块

import datetime
print(datetime.date.today())  # 2021-11-25
print(datetime.datetime.today())  # 2021-11-25 12:15:11.969769
"""date年月日  datetime年月日时分秒  time时分秒(MySQL django后期可以)"""
res = datetime.datetime.today()
print(res.year)  # 2021
print(res.month)  # 11
print(res.day)  # 25
print(res.weekday())  # 获取星期(weekday星期是0-6) 0表示周一
print(res.isoweekday())  # 获取星期(weekday星期是1-7) 1表示周一
"""时间差(timedelta)"""
ctime = datetime.datetime.today()
time_tel = datetime.timedelta(days=3)
print(ctime)  # 2021-11-25 12:20:48.570489
print(ctime - time_tel)  # 2021-11-22 12:21:06.712396
print(ctime + time_tel)  # 2021-11-28 12:21:06.712396
"""
日期对象 = 日期对象 +/- timedelta对象
timedelta对象 = 日期对象 +/- 日期对象
"""
ret = ctime + time_tel
print(ret - ctime)  # 3 days, 0:00:00
print(ctime - ret)  # -3 days, 0:00:00

相关