1. 程式人生 > 其它 >re模組補充、collections、time與datetime、random

re模組補充、collections、time與datetime、random

今日內容總結

一、re模組的其他知識

二、collections模組

三、time與datetime模組

四、random模組

一、re模組補充說明

import re
ret = re.findall('(a)bc', 'abcabcabcabc')
print(ret)
ret = re.findall('a(?:b)c', 'abcabcabcabc')
print(ret)
ret = re.findall('(a)(b)(c)', 'abcabcabc')
print(ret)
ret = re.findall('(?P<aaa>a)(b)(c)', 'abcabcabc')
print(ret)

""" 
  findall預設的是分組優先展示,所以如果正則表示式有括號分組,在展示結果的時候,預設只演示括號內正則表示式匹配到的內容。
  所以我們也可以取消分組有限展示的極致
   (?:)  括號前面加問號冒號
"""
import re
ret = re.search('(a)b(c)','abcabcabcabc')
print(ret.group())
print(ret.group(0))  # 通過索引的方式單獨獲取分組內匹配到的資料
print(ret.group(1))
print(ret.group(2))
''' 
   search和match裡面有幾個分組,group方法括號內最大就能寫到幾
'''

# 分組也可以給組起別名
import re
ret = re.search('a(?P<name1>b)(?P<name2>c)', 'abcabcabcabc')
print(ret.group('name1'))  # b
print(ret.group('name2'))  # c
# 通過名字對應來取值

二、collections模組

1、具名元組namedtuple

from collections import namedtuple  # 使用from...import..的方式直接呼叫模組裡面的功能
# 1、建立一個元組物件模板
point = namedtuple('座標',['x','y'])
# 2、建立諸多元組資料
p1 = point(1, 2)
p2 = point(3, 4)
print((p1, p2))
person = namedtuple('嘉賓','name age number')
person1 = person('熊大',10,1)
person2 = person('熊二',9,2)
print(person1, person2)
# 直接獲取person1中的年齡
print(person1.age)

# 根據具名元組的這個特性,它的使用也相對廣泛,例如在數學領域和娛樂領域等
# 獲取撲克的點數
from collections import namedtuple
card = namedtuple('撲克牌',['花色', '點數'])
c1 = card('黑桃♠', '3')
c2 = card('梅花♣', '2')
c3 = card('方塊◇', 'k')
print(c1, c2, c3)
# 直接檢視點數
print(c2.點數)

2、雙端佇列deque

佇列:先進先出, 預設是隻有一端進,一端出
雙端佇列:兩端都可以進出
import queue
q = queue.Queue(3)  # 最多隻能放三個元素
import queue
q = queue.Queue(3)
q.put(111)
q.put(222)
q.put(333)
print(q.get())  # 111
print(q.get())  # 222
print(q.get())  # 333
#  如果佇列增加滿了,繼續增加程式就會原地等待

from collections import deque
q = deque([11, 22, 33])
print(q)
q.append(44)  # 從後面增加,也就是從右邊增加
print(q)
q.appendleft(123)  # 從左邊增加
print(q)
q.pop()
print(q)  # 從後面彈出,也就是右邊
q.popleft()  # 從左邊彈出
print(q)

3 、字典相關

# 字典的內部是無序的
d1 = dict([('name', 'jason'), ('pwd', 123), ('hobby', 'study')])
print(d1)  # {'pwd': 123, 'name': 'jason', 'hobby': 'study'}

# 有序字典
from collections import OrderedDict
d1 = OrderedDict([('a', 1), ('b', 2), ('c', 3)])
print(d1)
d1['x'] = 111
d1['y'] = 222
d1['z'] = 333
print(d1)

小練習:
"""
有如下值集合 [11,22,33,44,55,67,77,88,99,999],
將所有大於 66 的值儲存至字典的第一個key中,將小於 66 的值儲存至第二個key的值中。
"""
# 使用for迴圈來寫
l1 = [11,22,33,44,55,67,77,88,99,999]
new_d = {'k1':[], 'k2':[]}  # 大於66存k1,否則存k2
for i in l1:
    if i > 66:
        new_d['k1'].append(i)
    else:
        new_d['k2'].append(i)
print(new_d)
# {'k1': [67, 77, 88, 99, 999], 'k2': [11, 22, 33, 44, 55]}


# 使用defaultdict
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)
print(my_dict)

4 、計數器 Counter

# 統計字串裡面字元出現的次數
res = 'ababbbababcab'
# 使用for迴圈
new_dict = {}
for i in res:
    if i not in new_dict:
        new_dict[i] = 1
    else:
        new_dict[i] += 1
print(new_dict)  # {'a': 5, 'b': 7, 'c': 1}


# 使用counter
from collections import Counter
n = Counter(res)
print(n)  # Counter({'b': 7, 'a': 5, 'c': 1})
print(r.get('a'))  # 5
# 可以根據按key取值

三、time與datetime模組

1、time模組

# 常用模組
1、time.sleep(secs)  # secs就是推遲的秒數
  推遲指定時間執行,單位為秒
2、time.tiem
獲取當前時間戳


# 三種用於表示時間的格式(彼此之間可以轉換)
  1、時間戳
    距離1970年0時0分0秒帶現在的秒數
    time.time()
  2、結構化時間
    這個時間型別主要是給計算機看的
    time.localtime()

3、格式化時間
時間格式  2000/1/21 11:11:11
time.strftime()
'%Y-%m-%d %H:%M:%S' # 2022-03-29 19:04:35
'%Y-%m-%d %X'  # 2022-03-29 19:05:05

2、時間型別的轉換

格式化時間	<==> 結構化時間 <==>	 時間戳

# 時間戳<-->結構化時間
	gmtime
  localtime
# 結構化時間<-->格式化時間
	strftime
	strptime
  	time.strptime("2017-03-16","%Y-%m-%d")
    time.strptime("2017/03","%Y/%m")  前後必須一致
ps:UTC時間比我們所在的區域時間早八個小時(時區劃分)

3、datetime模組

# 呼叫模組
import datetime
print(datetime.date.today())  # 2022-03-29
print(datetime.datetime.today())  # 2022-03-29 19:18:33.156460
"""  
date   獲取的是年月日
datetime  獲取的是年月日時分秒
"""
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
"""
針對時間計算的公式
    日期物件 = 日期物件 +/- timedelta物件
    timedelta物件 = 日期物件 +/- 日期物件
"""
res = ctime + time_tel
print(res - ctime) 
# 4 days, 0:00:00

四、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)
 l1 = ['特等獎','一等獎','二等獎','三等獎','優秀獎']
 print(random.choice(l1))  # 隨機抽取一個 抽獎
print(random.sample(ll, 2))  # 隨機指定個數抽樣