re模块补充,collections,time, datetime, random模块

1. re模块的补充

  1. 分组

    findall默认是分组优先展示, 正则表达式中如果有括号分组 那么在展示匹配结果的时候,默认只演示括号内正则表达式匹配到的内容!

    那么我们也可以取消分组优先展示,(?:) 括号前面加问号冒号

import re
res = re.findall('c(a)t', 'python cat')
print(res)
# >>>['a']

res = re.findall('c(?:a)t', 'python cat')
print(res)
# >>>['cat']

res = re.findall('(c)(a)(t)', 'python cat')
print(res)
# >>>[('c', 'a', 't')]

res = re.findall('(?P<name>c)(a)(t)', 'python cat')
print(res)
# >>>[('c', 'a', 't')]
# print(res.group('name'))
# >>>报错

res = re.search('(?P<name>c)(a)(t)', 'python cat')
print(res)
# >>><re.Match object; span=(7, 10), match='cat'>
print(res.group('name'))
# >>>c
res = re.search('c(a)t', 'python cat')
print(res.group())
# >>>cat
print(res.group(0))
# >>>cat
print(res.group(1))  # 可以通过索引的方式单独获取分组内匹配到的数据
# >>>a

'''针对search和match有几个分组 group方法括号内最大就可以写几'''

  

  2. 起别名

    我们可以对某个匹配字符进行起别名,进行单独查找

import re

# 分组之后还可以给组起别名
res = re.search('c(?P<name1>a)(?P<name2>t)', 'python cat')
print(res.group('name1'))
# >>>a
print(res.group('name2'))
# >>>t

 

2. collections模块

  1. 具名元组

from collections import namedtuple

# 1.先产生一个元组对象模板
point = namedtuple('python_cat_location', ['小区', '位置'])
# 2.创建诸多元组数据
location = point('梦佑青年社区', '便利店门口')
print(location)
# >>>python_cat_location(小区='梦佑青年社区', 位置='便利店门口')
print(location.小区)
# >>>梦佑青年社区
print(location.位置)
# >>>便利店门口
person = namedtuple('人物', 'name age gender')
p1 = person('dragon', 20, 'male')
p2 = person('tank', 35, 'female')
print(p1, p2)
# >>>人物(name='dragon', age=20, gender='male') 人物(name='tank', age=35, gender='female')
print(p1.gender, p2.name)
# >>>male tank
"""具名元组的使用场景也非常的广泛 比如数学领域、娱乐领域等"""
card = namedtuple('扑克牌', ['花色', '点数'])
c1 = card('黑桃♠', 'A')
c2 = card('梅花♣', 'Q')
c3 = card('红心❤', 'J')
print(c1, c2, c3)
# >>>扑克牌(花色='黑桃♠', 点数='A') 扑克牌(花色='梅花♣', 点数='Q') 扑克牌(花色='红心❤', 点数='J')
print(c2.点数)
# >>>Q

   

  2. 双端队列

# 队列:先进先出   默认是只有一端只能进另外一端只能出
# 双端队列:两端都可以进出
import queue

python_cat = queue.Queue(3)  # 最大只能放三个元素
# 存放元素
python_cat.put('python cat')
python_cat.put('cat')
python_cat.put('python')
# python_cat.put('python_cat')
# >>>会卡主不动  因为队列满了 继续添加则原地等待
# 获取元素
print(python_cat.get())
# >>>python cat
print(python_cat.get())
# >>>cat
print(python_cat.get())
# >>>python
# print(python_cat.get())
# >>>会卡主不动  因为队列空了 继续获取则原地等待

from collections import deque

python_cat = deque(['python cat', 'cat', 'python'])
python_cat.append('print_cat')  # 右边添加元素
print(python_cat)
# >>>deque(['python cat', 'cat', 'python', 'print_cat'])
python_cat.appendleft('python_cat')  # 左边添加元素
print(python_cat)
# >>>deque(['python_cat', 'python cat', 'cat', 'python', 'print_cat'])
python_cat.pop()  # 右边弹出元素
print(python_cat)
# >>>deque(['python_cat', 'python cat', 'cat', 'python'])
python_cat.popleft()  # 左边弹出元素
print(python_cat)
# >>>deque(['python cat', 'cat', 'python'])

 

  3. 字典相关

# 正常的字典内部是无序的
dict1 = dict([('name', 'jason'), ('pwd', 123), ('hobby', 'study')])
print(dict1)
# >>>{'pwd': 123, 'name': 'jason', 'hobby': 'study'}
print(dict1)
# >>>{'name': 'jason', 'pwd': 123, 'hobby': 'study'}

# 有序字典
from collections import OrderedDict
dict2 = OrderedDict([('python_cat', 1), ('python cat', 2), ('cat', 3)])
print(dict2)
# >>>OrderedDict([('python_cat', 1), ('python cat', 2), ('cat', 3)])
dict2['tank'] = 'good'
dict2['dragon'] = 'great'
dict2['jason'] = 'bad'
print(dict2)
# >>>OrderedDict([('python_cat', 1), ('python cat', 2), ('cat', 3), ('tank', 'good'), ('dragon', 'great'), ('jason', 'bad')])
print(dict2.keys())
# >>>odict_keys(['python_cat', 'python cat', 'cat', 'tank', 'dragon', 'jason'])

"""
有如下值集合 [11,22,33,44,55,67,77,88,99,999],
将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
"""
from collections import defaultdict

values = [11, 22, 33, 44, 55, 67, 77, 88, 99, 90]
my_dict = defaultdict(list)  # 字典所有的值默认都是列表  {'':[],'':[]}
for value in values:
    if value > 66:
        my_dict['k1'].append(value)
    else:
        my_dict['k2'].append(value)

 

  4. 计数器

name = 'python_cat_print_bad'
'''
统计字符串中所有字符出现的次数
    {'p': 2, 'a': 2 ....}
'''
num_dict = {}
for i in name:
    if i not in num_dict:
        # 字符第一次出现 应该创建一个新的键值对
        num_dict[i] = 1
    else:
        num_dict[i] += 1
print(num_dict)
# >>>{'p': 2, 'y': 1, 't': 3, 'h': 1, 'o': 1, 'n': 2, '_': 3, 'c': 1, 'a': 2, 'r': 1, 'i': 1, 'b': 1, 'd': 1}

from collections import Counter
res = Counter(name)
print(res)
# >>>Counter({'t': 3, '_': 3, 'p': 2, 'n': 2, 'a': 2, 'y': 1, 'h': 1, 'o': 1, 'c': 1, 'r': 1, 'i': 1, 'b': 1, 'd': 1})
print(res.get('a'))  # 可以当成字典使用
# >>>2  直接获取key值对应的value

 

3. time模块

import time
# 1.常用方法
# 1. time.sleep(secs)
# 推迟指定的时间运行, 单位为秒
# ps: 该方法贯穿前后(基础、后期)
# 2. time.time()
# 获取当前时间戳

# 2.三种用于表示时间的格式(彼此之间可以转换)
# 1. 时间戳
# 距离1970年1月1日0时0分0秒至此相差的秒数
print(time.time())
# >>>1648545628.9787252
# 2. 结构化时间
# 该时间类型主要是给计算机看的, 人看起来不太方便
print(time.localtime())
# >>>time.struct_time(tm_year=2022, tm_mon=3, tm_mday=29, tm_hour=17, tm_min=20, tm_sec=43, tm_wday=1, tm_yday=88, tm_isdst=0)
# 0 tm_year(年)    比如2011
# 1 tm_mon(月)    1 - 12
# 2 tm_mday(日)    1 - 31
# 3 tm_hour(时)    0 - 23
# 4 tm_min(分)    0 - 59
# 5 tm_sec(秒)    0 - 60
# 6 tm_wday(weekday)    0 - 6(0表示周一)
# 7 tm_yday(一年中的第几天)    1 - 366
# 8 tm_isdst(是否是夏令时)    默认为0
# 3. 格式化时间
# 人最容易接收的一种时间格式
# 2000 / 1 / 21 11: 11:11
# time.strftime()
# '%Y-%m-%d %H:%M:%S'  # 2022-03-29 11:31:30
# '%Y-%m-%d %X'  # 2022-03-29 11:31:30
# % 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)
# % a 本地简化星期名称
# % A 本地完整星期名称
# % b 本地简化的月份名称
# % B 本地完整的月份名称
# % c 本地相应的日期表示和时间表示
# % j 年内的一天(001 - 366)
# % p 本地A.M.或P.M.的等价符
# % U 一年中的星期数(00 - 53)星期天为星期的开始
# % w 星期(0 - 6),星期天为星期的开始
# % W 一年中的星期数(00 - 53)星期一为星期的开始
# % x 本地相应的日期表示
# % X 本地相应的时间表示
# % Z 当前时区的名称
# % % % 号本身
"""
记住一些常用的即可 其他的全部记录到自己的博客 以后能找到就行!!!
"""

 

4. 时间类型的转换

# 格式化时间    <==> 结构化时间 <==>     时间戳

# 时间戳<-->结构化时间
# gmtime
#  localtime
# 结构化时间<-->格式化时间
# strftime
# strptime
# time.strptime("2017-03-16","%Y-%m-%d")
# time.strptime("2017/03","%Y/%m")  前后必须一致

 

5. datetime模块

# 基本操作
import datetime
print(datetime.date.today())
# >>>2022-03-29
print(datetime.datetime.today())
# >>>2022-03-29 17:25:22.477221
"""
date                意思就是年月日
datetime            意思就是年月日 时分秒
ps:后期很多时间相关的操作都是跟date和time有关系
"""
res = datetime.date.today()
print(res.year)
# >>>2022
print(res.month)
# >>>3
print(res.day)
# >>>29
print(res.weekday())
# >>>1       星期0-6
print(res.isoweekday())
# >>>2    星期1-7

"""时间差"""
ctime = datetime.datetime.today()
time_tel = datetime.timedelta(days=5)   # 有很多时间选项
print(ctime)
# >>>2022-03-29 17:25:52.698438
print(ctime + time_tel)
# >>>2022-04-03 17:26:09.628119
print(ctime - time_tel)
# >>>2022-03-24 17:26:09.628119
"""
针对时间计算的公式
    日期对象 = 日期对象 +/- timedelta对象
    timedelta对象 = 日期对象 +/- 日期对象
"""
res = ctime + time_tel
print(res - ctime)  
# 5 days, 0:00:00

 

6. random模块

'''别名>>>:随机数模块'''
import random

print(random.random())  # 随机产生一个0到1之间的小数
# >>>0.5884910181679308
print(random.uniform(2, 4))  # 随机产生一个2到4之间的小数
# >>>2.840325783834003
print(random.randint(0, 9))  # 随机产生一个0到9之间的整数(包含0和9)
# >>>3
print(random.randint(1, 6))  # 掷骰子
# >>>2

index_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
random.shuffle(index_list)  # 随机打乱一个数据集合                       洗牌
print(index_list)
# >>>[5, 20, 10, 7, 13, 15, 16, 11, 4, 17, 14, 9, 19, 18, 12, 6, 1, 2, 8, 3]

str_list = ['python cat', 'python_cat', 'cat', 'print_python_cat']
print(random.choice(str_list))  # 随机抽取一个
# >>>python cat
str_list = ['python cat', 'python_cat', 'cat', 'print_python_cat']
print(random.sample(str_list, 2))  # 随机指定个数抽样
# >>>['python cat', 'cat']
print(random.sample(str_list, 3))  # 随机指定个数抽样
# >>>['print_python_cat', 'python_cat', 'python cat']

 

posted @ 2022-03-29 17:30  thrombus  阅读(34)  评论(0)    收藏  举报