上班的時候偷懶,把Python幫助里的標準功能庫1過了一遍,順便翻譯了一下,雖然我知道基本沒有人看,但不是說21世紀編程能力是基本的生存力嘛。
通過閱讀本文,你將了解Python的11個標準功能庫
1.操作系統接口庫
2.文件通配符
3.命令行參數
4.錯誤輸入重定向及終止程序
5.字符匹配
6.數學庫
7.互聯網訪問
8.日期與時間
9.數據壓縮
10.性能評價
11.質量控制
1.操作系統接口庫
OS操作系統模塊提供了一系列的與操作系統的交互。要盡可能確保使用Import os方式而不是from os import *. 這將使得保持os.open()映射自不同操作的內建的open()函數。內建的dir()和help()函數是在os大模塊中非常有用的輔助手段。
>>>import os
>>>os.getcwd()? #返回當前工作路徑
>>>os.chdir('/abc/abc') #改變當前的工作路徑
>>>os.system('mkdir today') #在系統命令行運行mkdir
>>>dir(os) #返回所有的功能模塊列表
>>>help(os) #返回創建自模塊文檔的手冊
對于日常的文件與目錄管理,更容易使用的shutil模塊能夠提供更高層次的接口。
>>>import shutil
>>>shutil.copyfile(src, dst, *, follow_symlinks=True)? #復制文件
>>>shutil.move(src, dst, copy_function=copy2)?#移動文件或目錄
2.文件通配符
glob模塊提供了一個通過使用通配符搜索目錄并生成文件清單的功能
>>>import glob
>>>glob.glob('*.py') #返回后綴是py的所有文件列表
3.命令行參數
一般的腳本工具都需要處理命令行參數。這些參數都以列表的形式存放在sys模塊的argv屬性中。下面的例子是在命令行運行python demo.py one two three的輸出結果:
>>>import sys
>>>print(sys.argv)
['demo.py','one','two','three']
getopt模塊會根據協議,通過使用Unix的getopt()函數來處理sys.argv。argparse提供了更強大和更有彈性的處理命令行程序。
4.錯誤輸入重定向及終止程序
sys模塊還具有stdin,stdout和stderr屬性,其中stderr主要用于彈出警告與錯誤信息,并使它們可視化,就算當stdout已經被重定向了。
>>>sys.stderr.write('Warning message')
最常用的結束腳本運行的命令是sys.exit()
5.字符匹配
re模塊提供了常用的高級字符處理工具。對于復雜的匹配與處理,常規表達式提供了簡明的方案:
>>> import re
>>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
['foot', 'fell', 'fastest']
>>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat')
'cat in the hat'
當如果只需要簡單功能時,可以直接使用字符串,因為這樣易讀和易于調試。
>>> 'tea for too'.replace('too', 'two')
'tea for two'
6.數學庫
math模塊提供了處理浮點運算時訪問C語言庫的能力
>>> import math
>>> math.cos(math.pi / 4)
0.70710678118654757
>>> math.log(1024, 2)
10.0
random模塊提供了隨機選擇工具
>>> import random
>>> random.choice(['apple', 'pear', 'banana']) #隨機選擇列表項
'apple'
>>> random.sample(range(100), 10)?? # 100以內的10個隨機數樣本
[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
>>> random.random()??? # 隨機浮點數
0.17970987693706186
>>> random.randrange(6)??? # 6以內的隨機整數
4
statistics模塊提供了基礎的數值統計功能(平均數、中間數、偏差等)
>>> import statistics
>>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
>>> statistics.mean(data)
1.6071428571428572
>>> statistics.median(data)
1.25
>>> statistics.variance(data)
1.3720238095238095
在SciPy項目中<https://scipy.org>有許多做其它數值運算的模塊。
7.互聯網訪問
有許多模塊能夠提供了訪問互聯網和處理網絡協議,有兩個最簡單的,urllib.request是從URLs來接收數據,smtplib用于發送郵件(需要郵件服務器的支持)
>>> from urllib.request import urlopen
>>> with urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl') as response:
... ??? for line in response:
... ??????? line = line.decode('utf-8')? # Decoding the binary data to text.
... ??????? if 'EST' in line or 'EDT' in line:? # look for Eastern Time
... ??????????? print(line)
<BR>Nov. 25, 09:43:32 PM EST
>>> import smtplib
>>> server = smtplib.SMTP('localhost')
>>> server.sendmail('soothsayer@example.org', 'jcaesar@example.org',
... """To: jcaesar@example.org
... From: soothsayer@example.org
...
... Beware the Ides of March.
... """)
>>> server.quit()
8.日期與時間
datetime模塊提供了多種處理日期與時間的類,支持日期與時間的數值運算,主要加強了數值運算效率與輸出格式的處理。這個模塊也支持時區對象。
>>> # 簡單的日期建立與格式化
>>> 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.'
>>> # 支持日歷運算的日期
>>> birthday = date(1964, 7, 31)
>>> age = now - birthday
>>> age.days
14368
9.數據壓縮
常見的數據歸檔與壓縮支持模塊:zlib,gzip,bz2,lzma,zipfile,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
10.性能評價
有些Python開發者在開發過程中,想知道不同的方法導致的性能上的差異有多大,系統提供了測量工具來即時回答這個問題。舉個例子,使用數組的打包與解包特性來替代傳統的清理參數的方法具有很強的吸引力,timeit模塊可以快速展示性能的優勢:
>>> from timeit import Timer
>>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()
0.57535828626024577
>>> Timer('a,b = b,a', 'a=1; b=2').timeit()
0.54962537085770791
相比于timeit的精細層面,profile和pstats模塊提供了工具來識別大塊代碼的時間消耗。
11.質量控制
一個開發高質量軟件的方法是對每個功能寫出測試案例,并在開發時經常運行測試。doctest模塊提供一個嵌入式工具來掃描和校驗測試。測試的構建和剪切粘貼一樣的簡單。通過提供用戶一個例子和它允許doctest模塊來確認代碼對于文檔來講仍然為真,來優化文檔。
def average(values):
??? """Computes the arithmetic mean of a list of numbers.
>>> print(average([20, 30, 70]))
40.0
"""
??? return sum(values) / len(values)
import doctest
doctest.testmod()?? # 自動檢驗嵌入式測試
unittest不是象doctest一樣毫不費力的,它允許更多的強化整體測試,通過把測試維護在單獨的文件里。
import unittest
class TestStatisticalFunctions(unittest.TestCase):
??? def test_average(self):
??????? self.assertEqual(average([20, 30, 70]), 40.0)
??????? self.assertEqual(round(average([1, 5, 7]), 1), 4.3)
??????? with self.assertRaises(ZeroDivisionError):
??????????? average([])
??????? with self.assertRaises(TypeError):
??????????? average(20, 30, 70)
unittest.main()? # Calling from the command line invokes all tests