re模块、time模块、collections模块、random模块

本章内容

  • re模块的其他知识
  • 正则的别名及分组机制
  • collections模块
  • time与datetime模块
  • random随机数模块

rem模块的其他知识

1.findall的分组优先展示:
# 默认优先展示表达式括号内的内容 eg:
    res = re.findall('a(b)cd','abcdefg')  # 只展示['b']
    res = re.findall('a(b)(c)','abcdef') # [('b','c')] 
# 也可以取消分组优先展示的机制
	res = re.findall('a(?:b)c','abcd')  # ['abc']  
image-20220329153424292
# findall没有group方法 eg:
   ret = re.findall('(?P<aaa>a)(b)(c)','abcabcabcabc')
   print(ret)               # 正确调用
   print(ret.group('aaa'))  # 错误调用
image-20220329153737371
2.search方法也可以实现优先显示 eg:
    res = re.search('a(b)c','abcabcabcabc')
	print(res.group(0))
	print(res.group(1))
	res = re.search('a(b)(c)','abcabcabcabc')
	print(res.group(0))
	print(res.group(1))
	print(res.group(2))	
# 其实就是通过索引的方式单独获取分组内匹配到的数据,有几个组,括号内最大就可以写几

"""search 和 match 都适用次方法"""	
image-20220329154617764
# 分组之后还可以给分组起别名 eg:
	res = re.search('a(?P<name1>b)(c)','abcabcabcabc')
	print(res.group('name1'))
image-20220329155732231

collection模块

"""collections其实就是给用户提供了更多的数据类型"""
1.具名元组 eg:
    from collections import namedtuple
    point = namedtuple('person',('name','age'))
    p1 = point('jason',19)
    print(p1)
image-20220329163519871
"""
具名元组的使用场景也非常的广泛 比如数学邻域、娱乐领域
"""
eg: 扑克牌
    from collections import namedtuple
    card = namedtuple('扑克牌',('花色','点数'))
    c1 = card('❤',8)
    c2 = card('♣',10)
    c3 = card('♦','J')
    print(c1,c2,c3)
    print(c3.花色)
image-20220329164540972
2.双端队列 (deque)
    队列(queue):先进先出 默认是只有一端能进另外一端能出
    双端队列(deque):两端都可以进出
	import queue
    q = queue.Queue(3)
    q.put('jason')
    q.put(18)
    q.put(666)
    print(q.get())
    print(q.get())
    print(q.get())
# 如果队列里的元素取完,则会继续执行,直到新的元素传入 
image-20220329165903185
"""双端队列(deque)"""
from collections import deque
num = deque(['jason'])
num.append(18)
num.appendleft(666)  # 左边添加 666
print(num)
num.popleft()    # 左边弹出 666
num.pop()
print(num)
image-20220329171014765
3.字典相关
# 正常的字典内部是无序的
"""字典"""
d1 = dict([('name', 'tony'), ('age', 18), ('gender', 'male')])
print(d1)
"""有序字典"""
from collections import OrderedDict
d2 = OrderedDict([('name', 'tony'), ('age', 18), ('gender', 'male')])
print(d2)
print(d2.keys())
image-20220329173018078
# 需求:
	有如下值集合 [11,22,33,44,55,67,77,88,99,999],
	将所有大于 66 的值保存至字典的第一个key中,将小于 66 	的值保存至第二个key的值中。
l1 = [11,22,33,44,55,67,77,88,99,999]
new_dict = {'k1':[],'k2':[]}
for i in l1:
    if i > 66:
        new_dict['k1'].append(i)
    else:
        new_dict['k2'].append(i)
print(new_dict)

from collections import defaultdict
values = [11,22,33,44,55,67,77,88,99,999]
my_dict = defaultdict(list)
for d in values:
    if d > 66:
        my_dict['k1'].append(d)
    else:
        my_dict['k2'].append(d)
print(my_dict)
image-20220329174123061
4.计数器
"""计数器"""
num = '2178127982319387129891298'
new_dict = {}
for i in num:
    if i not in new_dict:
        new_dict[i] = 1
    else:
        new_dict[i] += 1
print(new_dict)
"""Counter"""
num = '2178127982319387129891298'
from collections import Counter
r = Counter(num)
print(r)
"""还可以当成字典使用"""
print(r.get('1'))
image-20220329182310880

time模块

1.常用方法
	1.1 time.sleep()
	让运行的代码在此处睡眠一段时间(单位为秒),结束后再运行
    1.2 time.time()
    获取当前时间戳
2.三种用于表示时间的格式(彼此之间可以转换)
	2.1时间戳
    	距离1970年1月1日0时0分0秒至此相差的秒数
    2.2 结构化时间
    	该时间类型主要是给计算机看的,人看起来不太方便
          time.localtime()
          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
image-20220329184637220
	2.3 格式化时间
    	%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 当前时区的名称
        %% %号本身
    print(time.strftime('%Y-%m-%d %H:%M:%S'))
    print(time.strftime('%Y-%m-%d %X'))
image-20220329184929711

时间类型的转换

img

常用时间类型之间的转换

常用的时间类型有 时间戳(int/float),struct_time对象,datetime.date对象,datetime.datetime对象

Str格式 和 时间戳

# 使用time 由 str 转换为 时间戳
timeStr = '2020-12-31 09:30:18'
timeArray = time.strptime(timeStr, "%Y-%m-%d %H:%M:%S")
timeStamp = time.mktime(timeArray)
print(timeStamp)  # 1609378218.0

# 使用datetime 由 str 转换为 时间戳
dateArray = datetime.datetime.strptime(timeStr, "%Y-%m-%d %H:%M:%S")
timeStamp = dateArray.timestamp()
print(timeStamp)  # 1609378218.0

# 使用time 由 时间戳 转换为 str
timeStamp = 1609378218
timeArray = time.localtime(timeStamp)
timeStr = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print(timeStr)  # 2020-12-31 09:30:18

# 使用datetime 由 时间戳 转换为 str
dateArray = datetime.datetime.fromtimestamp(timeStamp)
timeStr = dateArray.strftime("%Y-%m-%d %H:%M:%S")
print(timeStr)  # 2020-12-31 09:30:18
image-20220329220452204

datetime对象和时间戳

# 由 时间戳 转换为 datetime对象 (转换为 str格式)
timeStamp = 1609378218
dateArray = datetime.datetime.fromtimestamp(timeStamp)
timeStr = dateArray.strftime("%Y-%m-%d %H:%M:%S")
print(timeStr)   # 2020-12-31 09:30:18

# 使用datetime,指定utc时间,相差8小时
timeStamp = 1609378218
dateArray = datetime.datetime.utcfromtimestamp(timeStamp)
timeStr = dateArray.strftime("%Y-%m-%d %H:%M:%S")
print(timeStr)   # 2020-12-31 09:30:18

# 由 datetime对象 转换为 时间戳
dateArray = datetime.datetime(year=2020, month=12, day=31, hour=9, minute=30, second=18)
timeStamp = dateArray.timestamp()
print(timeStamp)  # 1609378218.0
image-20220329220537758

str类型转换为其他格式的str

# 原始字符类型的时间
ts = '2020-12-31 09:30:18'
# 转为struct_time
timeArray = time.strptime(ts, "%Y-%m-%d %H:%M:%S")
# 转为其它显示格式
timeStr = time.strftime("%Y/%m/%d %H:%M:%S", timeArray)
print(timeStr)
image-20220329220610776

datetime模块

import datetime
print(datetime.date.today())
print(datetime.datetime.today())
image-20220329195348116
import datetime
res = datetime.date.today()
print(res.year)
print(res.month)
print(res.day)
print(res.weekday())       # 默认0-6
print(res.isoweekday())    # 默认1-7
image-20220329203442375
"""时间差"""
import datetime
d_time = datetime.datetime.today()
few_time = datetime.timedelta(days=3)
print(d_time - few_time)
print(d_time + few_time)
"""
针对时间计算的公式
    日期对象 = 日期对象 +/- timedelta对象
"""
image-20220329204953666
"""
timedelta对象 = 日期对象 +/- 日期对象
"""
res = d_time + few_time
print(res - d_time)
image-20220329205155486

random模块

'''别名>>>:随机数模块'''
import random
# print(random.random())  #  随机产生一个0到1之间的小数
# print(random.uniform(2,4))  # 随机产生一个2到4之间的小数
# print(random.randint(0,9))  # 随机产生一个0到9之间的整数(包含0和9)
# print(random.randint(1,6))  #                              掷骰子
# l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
# random.shuffle(l)  # 随机打乱一个数据集合                       洗牌
# print(l)
# ll1 = ['特等奖','张飞抱回家','如花','百万现金大奖','群内配对']
# print(random.choice(ll1))  # 随机抽取一个                     抽奖
ll = ['如花','C老师','R老师','J老师','M老师','张飞','龙龙']
print(random.sample(ll, 2))  # 随机指定个数抽样                 抽样
image-20220329211017735
posted @ 2022-03-29 21:12  DDYT  阅读(173)  评论(0)    收藏  举报