- 取消转义
- python内置模块之re
- re实战之爬取红牛分公司数据
- collections模块(python其他数据类型)
- time与datetime模块
一、取消转义
在原生的正则表达式中取消转义推荐使用\(每个\只能取消一个字符的转义)
在python中取消转义推荐使用r'\n\a\t'(也可以使用\)
二、python内置模块之re模块
# 在python要想使用正则必须借助于模块 re就是其中之一
'''基本操作方法'''
import re
1.findall()
re.findall('正则表达式','带匹配的文本')
# 根据正则匹配除所有符合条件的数据
# res = re.findall('b','eva jason jackson') # []
# res = re.findall('a','eva jason jackson') # ['a', 'a', 'a']
# print(res) # 结果是一个列表(要么有元素 要么空列表)
2.search()
res = re.search('正则表达式', '待匹配的文本')
# 根据正则匹配到一个符合条件的就结束
res = re.search('a','eva jason jackson')
print(res) # 结果对象 <_sre.SRE_Match object; span=(2, 3), match='a'>
print(res.group()) # 匹配到的结果 a
# if res:
# print(res.group())
# else:
# print('不好意思 没有找到')
res = re.search('m', 'eva jason jackson')
print(res) # None
"""如果没有符合条件的数据 那么search返回None 并且使用group会直接报错"""
3.match()
res = re.match('a', 'abc').group() # 同search,不过仅在字符串开始处进行匹配
print(res) # 结果 a
4.split()
# 先按'a'分割得到''和'bcd',在对''和'bcd'分别按'b'分割
# res = re.split('[ab]','abcd')
# print(res) # ['', '', 'cd']
5.sub()
# 类似于字符串类型的replace方法
# res = re.sub('\d','$','eva3jason4yuan4',1) # eva$jason4yuan4 替换正则匹配到的内容
# res = re.sub('\d','$','eva3jason4yuan4') # eva$jason$yuan$ 不写默认替换所有
# print(res)
6.subn()
"""返回元组 并提示替换了几处"""
# res = re.subn('\d', '$', 'eva3jason4yuan4') # ('eva$jason$yuan$', 3)
res = re.subn('\d', '$', 'eva3jason4yuan4', 1) # ('eva$jason4yuan4', 1)
print(res)
常用
'''常用'''
# compile()
obj = re.compile('\d{3}') # 将正则表达式编译成为一个 正则表达式对象,规则要匹配的是3个数字
ret = obj.search('abc123eeee') # 正则表达式对象调用search,参数为待匹配的字符串
print(ret.group()) # 结果 : 123
'''常用'''
# finditer()
# finditer返回一个存放匹配结果的迭代器
res = re.finditer('\d+','ashdklah21h23kj12jk3klj112312121kl131')
print([i.group() for i in res])
# ['21', '23', '12', '3', '112312121', '131']
'''findall优先级'''
ret = re.findall('www.(baidu|oldboy).com', 'www.oldboy.com')
print(ret) # ['oldboy']
# 这是因为findall会优先把匹配结果组里内容返回,如果想要匹配结果,取消权限即可
ret = re.findall('www.(?:baidu|oldboy).com', 'www.oldboy.com')
print(ret) # ['www.oldboy.com']
# res = re.findall("^[1-9]\d{14}(\d{2}[0-9x])?$",'110105199812067023')
# print(res) # ['023']
# 取消分组优先展示
# res1 = re.findall("^[1-9](?:\d{14})(?:\d{2}[0-9x])?$",'110105199812067023')
# print(res1)
'''split优先级'''
ret=re.split("\d+","eva3egon4yuan")
print(ret) #结果 : ['eva', 'egon', 'yuan']
ret=re.split("(\d+)","eva3egon4yuan")
print(ret) #结果 : ['eva', '3', 'egon', '4', 'yuan']
#在匹配部分加上()之后所切出的结果是不同的,
#没有()的没有保留所匹配的项,但是有()的却能够保留了匹配的项,
#这个在某些需要保留匹配部分的使用过程是非常重要的。
# 有名分组
res = re.search('^[1-9](?P<x>\d{14})(?P<o>\d{2}[0-9x])?$', '123456789098765432')
print(res) # <_sre.SRE_Match object; span=(0, 18), match='123456789098765432'>
print(res.group()) # 123456789098765432
print(res.group(1)) # 23456789098765
print(res.group('x')) # 23456789098765
print(res.group('o')) # 432
三、正则实战案例之爬取红牛分公司数据
import re
# 读取带匹配的数据
with open(r'a.txt', 'r', encoding='utf8') as f:
data = f.read()
# 利用正则匹配数据
# 分公司名称
title_list = re.findall('<h2>(.*?)</h2>', data)
# print(title_list)
# 分公司地址
address_list = re.findall("<p class='mapIco'>(.*?)</p>", data)
# print(address_list)
# 分公司邮箱
email_list = re.findall("<p class='mailIco'>(.*?)</p>", data)
# print(email_list)
# 分公司电话
phone_list = re.findall("<p class='telIco'>(.*?)</p>", data)
res = zip(title_list, address_list, email_list, phone_list)
for data_tuple in res:
print("""
公司名称:%s
公司地址:%s
公司邮箱:%s
公司电话:%s
""" % (data_tuple[0], data_tuple[1], data_tuple[2], data_tuple[3]))
四、collections模块
# 该模块内部提供了一些高阶的数据类型
1.namedtuple(具名元组)
from collections import namedtuple
"""
namedtuple('名称',[名字1, 名字2,...])
namedtuple('名称',"名字1 名字2...")
"""
# point = namedtuple('坐标', ['x', 'y'])
# res = point(11, 22)
# print(res) # 坐标(x=11, y=22)
# print(res.x) # 11
# print(res.y) # 22
# point = namedtuple('坐标', 'x y z')
# res = point(11, 22, 33)
# print(res) # 坐标(x=11, y=22, z=33)
# print(res.x) # 11
# print(res.y) # 22
# print(res.z) # 33
# card = namedtuple('扑克', '花色 点数')
# card1 = card('♠', 'A')
# card2 = card('♥', 'K')
# print(card1)
# print(card1.花色)
# print(card1.点数)
2.队列
import queue # 内置队列模块: FIFO
# 初始化队列
q = queue.Queue()
# 往队列中添加元素
q.put('first')
q.put('second')
q.put('third')
# 从队列中获取元素
print(q.get())
print(q.get())
print(q.get())
print(q.get()) # 值去没了就会原地等待
3.双端队列
from collections import deque
q = deque([1, 2, 3])
q.append(4)
q.appendleft(5)
print(q) # deque([5, 1, 2, 3, 4])
q.pop
print(q) # 从右边取值
q.popleft()
print(q) # 从左边取值
4.有序字典
normal_dict = dict([('name', 'jason'), ('pwd', 123), ('hobby', 'study')])
print(normal_dict)
# {'hobby': 'study', 'pwd': 123, 'name': 'jason'}
from collections import OrderedDict
order_dict = OrderedDict([('name', 'jason'), ('pwd', 123), ('hobby', 'study')])
print(order_dict) # OrderedDict([('name', 'jason'), ('pwd', 123), ('hobby', 'study')])
order_dict['xxx'] = 111
print(order_dict) # OrderedDict([('name', 'jason'), ('pwd', 123), ('hobby', 'study'), ('xxx', 111)])
5.默认值字典
from collections import defaultdict
values = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90]
my_dict = defaultdict(list)
for value in values:
if value > 60:
my_dict['k1'].append(value)
else:
my_dict['k2'].append(value)
print(my_dict)
# defaultdict(<class 'list'>, {'k2': [11, 22, 33, 44, 55], 'k1': [66, 77, 88, 99, 90]})
6.计数器
res = 'abcdeabcdabcaba'
# 统计字符串中每个元素出现的次数
# new_dict = {}
# for i in res:
# if i not in new_dict:
# new_dict[i] = 1
# else:
# new_dict[i] += 1
# print(new_dict)
from collections import Counter # 计数器
ret = Counter(res)
print(ret)
# Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})
五、time模块
"""
时间三种表现形式
1.时间戳(秒数)
2.结构化时间(一般是给机器看的)
3.格式化时间(一般是给人看的)
三种时间是可以相互转换的!!!
"""
1.time.sleep() # 原地阻塞指定的秒数
2.time.time() # 获取时间戳时间
import time
print(time.strftime('%Y-%m-%d')) # 2021-11-25
%y 两位数的年份表示(00-99)
%Y 四位数的年份表示(000-9999)
%m 月份(01-12)
%d 月内中的一天(0-31)
%H 24小时制小时数(0-23)
%I 12小时制小时数(01-12)
%M 分钟数(00=59)
%S 秒(00-59
# print(time.time())
print(time.gmtime(11111111111))
# print(time.localtime())
![image]()
六、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
# 小练习 计算举例今年过生日还有多少天
# birthday = datetime.date(2000, 11, 11)
# now_date = datetime.date.today()
# days = birthday - now_date
# print('距离生日还有{}天'.format(days))
# UTC时间与我们的东八区时间差 八个小时
# print(datetime.datetime.now()) # 2021-11-25 12:25:33.579310
# print(datetime.datetime.utcnow()) # 2021-11-25 04:25:33.579310