1. 程式人生 > >python學習筆記-模組

python學習筆記-模組

pickle 模組

pickle模組實現了基本的資料序列和反序列化。
通過pickle模組的序列化操作我們能夠將程式中執行的物件資訊儲存到檔案中去,永久儲存。
通過pickle模組的反序列化操作,我們能夠從檔案中建立上一次程式儲存的物件。
基本介面:pickle.dump(obj, file, [,protocol])
讀取方式開啟檔案:x = pickle.load(file)

import pickle

pkl_file = open('data.pkl', 'rb')
data1 = pickle.load(pkl_file) #使用pickle模組從檔案中重構python物件
pprint.pprint(data1)

os作業系統介面

import os
os.getcwd()      # 返回當前的工作目錄
os.chdir('/server/accesslogs')   # 修改當前的工作目錄
os.system('mkdir today')   # 執行系統命令 mkdir 
dir(os)
help(os)
#針對日常的檔案和目錄管理任務,shutil 模組提供了一個易於使用的高階介面:
import shutil
shutil.copyfile('data.db', 'archive.db')
shutil.move('/build/executables', 'installdir')

glob檔案萬用字元

#glob模組提供了一個函式用於從目錄萬用字元搜尋中生成檔案列表
import glob
glob.glob('*.py') 

sys

通用工具指令碼經常呼叫命令列引數。這些命令列引數以連結串列形式儲存於 sys 模組的 argv 變數。

import sys
print(sys.argv)

re

re模組為高階字串處理提供了正則表示式工具。
re.match函式:從字串的起始位置匹配一個模式,起始位置匹配成功的話,match()就返回none
re.search方法:掃描整個字串並返回第一個成功的匹配
re.sub:替換字串中的匹配項
re.compile:編譯正則表示式,生成一個正則表示式( Pattern )物件,供 match() 和 search() 這兩個函式使用。
findall(string[, pos[, endpos]]):查詢所以匹配項,返回一個列表。字串:匹配長度
re.finditer:匹配的所有子串,並返回一個迭代器。
re.split:按照能夠匹配的子串將字串分割後返回列表

In [2]: import re

In [3]: re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
Out[3]: ['foot', 'fell', 'fastest']

In [47]: print(re.match('www', 'www.runoob.com'))
<re.Match object; span=(0, 3), match='www'>

In [48]: print(re.match('com', 'www.runoob.com'))
None
>>>import re
>>> pattern = re.compile(r'([a-z]+) ([a-z]+)', re.I)   # re.I 表示忽略大小寫
>>> m = pattern.match('Hello World Wide Web')
>>> print m                               # 匹配成功,返回一個 Match 物件
<_sre.SRE_Match object at 0x10bea83e8>
>>> m.group(0)                            # 返回匹配成功的整個子串
'Hello World'
>>> m.span(0)                             # 返回匹配成功的整個子串的索引
(0, 11)
>>> m.group(1)                            # 返回第一個分組匹配成功的子串
'Hello'
>>> m.span(1)                             # 返回第一個分組匹配成功的子串的索引
(0, 5)
>>> m.group(2)                            # 返回第二個分組匹配成功的子串
'World'
>>> m.span(2)                             # 返回第二個分組匹配成功的子串
(6, 11)
>>> m.groups()                            # 等價於 (m.group(1), m.group(2), ...)
('Hello', 'World')

math

random

import random
In [7]: random.choice(['apple', 'pear', 'banana'])
Out[7]: 'banana'

In [6]: random.sample(range(100), 10)
Out[6]: [78, 62, 92, 85, 56, 29, 99, 48, 38, 69]

random.random()    # 0-1 不含1隨機生成浮點數
random.randrange(6)  # 0-5範圍內隨機生成整數

訪問 網際網路

最簡單的兩個是用於處理從 urls 接收的資料的 urllib.request 以及用於傳送電子郵件的 smtplib

datetime

# weekday() 0-6表示週一-週日
In [8]: import datetime

In [9]: now = datetime.date.today()

In [10]: now
Out[10]: datetime.date(2018, 12, 24)
In [11]: print(now)
2018-12-24
In [12]: oneday=datetime.timedelta(days=1) # print(oneday) =1 day, 0:00:00
In [13]: yesterday = now -oneday

In [14]: yesterday
Out[14]: datetime.date(2018, 12, 23)
In [20]: monday = yesterday + datetime.timedelta(-yesterday.weekday()) #週一

In [21]: monday
Out[21]: datetime.date(2018, 12, 17)
In [24]: mondaystr = monday.strftime('%Y-%m-%d') #型別改為字串

In [25]: mondaystr
Out[25]: '2018-12-17'

In [27]: week = yesterday.strftime("%Y-%W") #本年度第幾周
 
In [28]: week
Out[28]: '2018-51'

zlib資料壓縮

直接支援通用的資料打包和壓縮格式:zlib,gzip,bz2,zipfile,以及 tarfile

In [32]: import zlib

In [33]: s = b'witch which has which witches wrist watch'

In [34]: len(s)
Out[34]: 41

In [35]:  t = zlib.compress(s)

In [36]: len(t)
Out[36]: 37

In [37]: zlib.decompress(t)
Out[37]: b'witch which has which witches wrist watch'

timeit效能度量

# 比較兩種方法實現a、b值互換花費的時間
In [39]: from timeit import Timer

In [40]: Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
Out[40]: 0.030674659999931464

In [41]: Timer('a,b = b,a', 'a=1; b=2').timeit()
Out[41]: 0.026684544998715864

測試模組

doctest、unittest

日曆模組

In [44]: import calendar

In [45]: print(calendar.month(2018,12))
   December 2018
Mo Tu We Th Fr Sa Su
                1  2
 3  4  5  6  7  8  9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31