本文將講解Python標(biāo)準(zhǔn)庫內(nèi)容,有操作系統(tǒng)接口os、文件路徑通配符glob、命令行參數(shù)sys、正則表達(dá)式re、數(shù)學(xué)math、日期與時(shí)間、數(shù)據(jù)壓縮、性能評(píng)估等,我們只需要知道有些什么內(nèi)容,用到時(shí)候再查找資料即可,無需熟記,也記不住。
一 操作系統(tǒng)接口及文件通配符
1-路徑操作
import os
os.getcwd()#獲取當(dāng)前路徑
os.chdir('../')#改變當(dāng)前路徑
os.getcwd()#獲取當(dāng)前路徑
2-不同操作系統(tǒng)有不同接口函數(shù)
有進(jìn)程參數(shù)、文件創(chuàng)建、進(jìn)程管理、調(diào)度等
具體參考:https://docs.python.org/3.6/library/os.html#module-os
3-文件通配符
import glob
glob.glob('*.py')#返回當(dāng)前路徑下所有py文件數(shù)組
適配查找文件
>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
>>> glob.glob('**/*.txt', recursive=True)
['2.txt', 'sub/3.txt']
>>> glob.glob('./**/', recursive=True)
['./', './sub/']
4-命令行參數(shù)
參考:https://docs.python.org/3.6/library/sys.html#module-sys
二 字符串匹配正則表達(dá)式
1-示例
>>> import re
>>> re.findall(r'bf[a-z]*', 'which foot or hand fell fastest')
#b表示匹配一個(gè)單詞邊界,也就是指單詞和空格間的位置。 f開始的單詞
['foot', 'fell', 'fastest']
>>> re.sub(r'(b[a-z]+) 1', r'1', 'cat in the the hat')
'cat in the hat'
2-正則表達(dá)式語法
re.match(pattern, string, flags=0)
更多參考:https://docs.python.org/3.6/library/re.html#module-re
三 數(shù)學(xué)計(jì)算與時(shí)間
1-math
涵括:數(shù)論計(jì)算、指數(shù)計(jì)算、三角函數(shù)、角度計(jì)算、雙曲線、常量等
直接傳入?yún)?shù)調(diào)用函數(shù)即可,比較簡單,請參考:https://docs.python.org/3.6/library/math.html#module-math
import math
math.gamma(0.5)#伽馬函數(shù)
math.pi#Π值
2-datetime
>>> # dates are easily constructed and formatted
>>> from datetime import date
>>> now = date.today()
>>> now
datetime.date(2003, 12, 2)
>>> now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")
'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'
>>> # dates support calendar arithmetic
>>> birthday = date(1964, 7, 31)
>>> age = now - birthday
>>> age.days
14368
四 數(shù)據(jù)壓縮
常見數(shù)據(jù)壓縮格式: zlib, gzip, bz2, lzma, zipfile and tarfile.
>>> import zlib
>>> s = b'witch which has which witches wrist watch'
>>> len(s)
41
>>> t = zlib.compress(s)
>>> len(t)
37
>>> zlib.decompress(t)
b'witch which has which witches wrist watch'
>>> zlib.crc32(s)
226805979
五 多線程
模塊:
- _thread(3.6之后不兼容了)
- threading(推薦使用)
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print ("開始線程:" + self.name)
print_time(self.name, self.counter, 5)
print ("退出線程:" + self.name)
def print_time(threadName, delay, counter):
while counter:
if exitFlag:
threadName.exit()
time.sleep(delay)
print ("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
# 創(chuàng)建新線程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# 開啟新線程
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print ("退出主線程")
Thread 對象的 Lock 和 Rlock 可以實(shí)現(xiàn)簡單的線程同步,Python 的 Queue 模塊中提供了同步的、線程安全的隊(duì)列類,包括FIFO(先入先出)隊(duì)列Queue,LIFO(后入先出)隊(duì)列LifoQueue,和優(yōu)先級(jí)隊(duì)列 PriorityQueue。更多參考:https://www.runoob.com/python3/python3-multithreading.html
六 弱引用
為了提高性能,采用弱引用方式調(diào)用對象,當(dāng)刪除對象的時(shí)候,自動(dòng)釋放內(nèi)存,引用失效。常用于創(chuàng)建對象耗時(shí)、緩存對象等。
>>> import weakref, gc
>>> class A:
... def __init__(self, value):
... self.value = value
... def __repr__(self):
... return str(self.value)
...
>>> a = A(10) # create a reference
>>> d = weakref.WeakValueDictionary()
>>> d['primary'] = a # does not create a reference
>>> d['primary'] # fetch the object if it is still alive
10
>>> del a # remove the one reference
>>> gc.collect() # run garbage collection right away
0
>>> d['primary'] # entry was automatically removed
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
d['primary'] # entry was automatically removed
File "C:/python36/lib/weakref.py", line 46, in __getitem__
o = self.data[key]()
KeyError: 'primary'
七 其他
還有l(wèi)ogging日志,array、collections數(shù)組集合工具、decimal浮點(diǎn)數(shù)運(yùn)算、reprlib輸出格式等等