python內建模組之re,time,collections
阿新 • • 發佈:2021-11-25
re 模組
import re
re.findall('a','eva again')# 根據正則找到所有a,並組織成列表的形式返回出來,找不到返回空列表
re.match('a','eva again')# 根據正則找開頭(必須是開頭),找到返回結果物件,需要用group()取到第一個a.使用group()時如果找不到會報錯.使用前需要經過處理,防止報錯程式崩潰
re.search('a','eva again') # 根據正則找到該字串中的a,只找一個,找到返回結果物件,找不到返回None.需要用group()取值,同時,找不到也會報錯.
re.split('[ab]','abcd') # 切割 先按照a切割得到' ','bcd',再按照b切割,得到一個列表[' ',' ',' cd']
re.sub('\d','h','a1b2c3d4',1) # 第一個引數\d代表取出數字,第二個引數代表要替換的,第三個引數是待處理的文字,第四個引數是處理多少個(預設是處理全部,這裡設定為1)得到'ahb2c3d4' 比較像之前講過字串的replace方法。
re.subn('\d','h','a1b2c3d4',1)# 同re.sub.返回結果是('ahb2c3d4', 1) 以元組形式,第二個元素是告訴我們替換了幾個,預設也是全部替換。 re.compile('')在括號內寫上一組正則表示式賦值給任意變數名,由該變數名通過句點符'.'的方式可以進行類似於findall,match,search操作,看下圖 res = re.finditer('\d+','ashdklah21h23kj12jk3klj112312121kl131') # 第一個引數是正則表示式取數字,第二個引數是待處理文字,將待處理裡的數字轉換成可迭代器物件 print([i.group() for i in res])# 可以用二元表示式迴圈取出組成列表。
分組優先機制
findall針對分組優先展示 無名分組
# 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)
有名分組
res = re.search('^[1-9](?P<xxx>\d{14})(?P<ooo>\d{2}[0-9x])?$','110105199812067023')# 通過?P<name> 進行分組<>內為組名,在用group方法列印對應的組名或索引 print(res) print(res.group()) # 直接取值返回所有結果:110105199812067023 print(res.group(1)) # 10105199812067 無名分組的取值方式(索引取) print(res.group(2)) # 返回:023 # 也可以通過組名取值 print(res.group('xxx')) # 返回:10105199812067 print(res.group('ooo')) # 返回:023
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([11,22,33])
q.append(44) # 從右邊新增
q.appendleft(55) # 從左邊新增
print(q.pop()) # 從右邊取值
print(q.popleft()) # 從做邊取值
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
order_dict
OrderedDict([('name', 'jason'), ('pwd', 123), ('hobby', 'study'), ('xxx', 111)])
normal_dict['yyy'] = 222
normal_dict
{'hobby': 'study', 'pwd': 123, 'yyy': 222, 'name': 'jason'}
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)
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)
time模組
"""
時間三種表現形式
1.時間戳(秒數)
2.結構化時間(一般是給機器看的)
3.格式化時間(一般是給人看的)
三種時間是可以相互轉換的!!!
"""
1.time.sleep() # 原地阻塞指定的秒數
2.time.time() # 獲取時間戳時間
import time
# 格式化時間
# print(time.strftime('%Y-%m-%d')) # 2021-11-25
# print(time.strftime('%Y-%m-%d %H:%M:%S')) # 2021-11-25 11:48:34
# print(time.strftime('%Y-%m-%d %X')) # 2021-11-25 11:48:34
"""
更多時間相關符號 儲存到容易查詢的位置即可
"""
# print(time.localtime())
# time.struct_time(
# tm_year=2021,
# tm_mon=11,
# tm_mday=25,
# tm_hour=11,
# tm_min=51,
# tm_sec=25,
# tm_wday=3,
# tm_yday=329,
# tm_isdst=0)
# print(time.time())
print(time.gmtime(11111111111))
# print(time.localtime())
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