Python 入門指南

單元 21 - 認識標準程式庫及 Tk

~~學習進度表~~

Python 已經內建大多數常用的功能,更多的功能都放在標準程式庫 (standard library)

Standard Library

Tk

下表列出官方 Library Reference 整理的所有模組分類

分類說明
Built-in Functions介紹所有內建函數。
Built-in Constants介紹所有內建常數,包括 False 、 True 、 None 等。
Built-in Types介紹所有內建型態及真假值計算,內建型態包括 int 、 float 、 complex 、迭代器、 list 、 tuple 、 range 、 str 、 bytes 、 bytearray 、 memoryview 、 set 、 frozenset 、 dict 及內容管理員、模組、類別、函數、方法等型態,真假值計算包括真值測試及布林運算等。
Built-in Exceptions介紹所有內建的例外類別。
Text Processing Services介紹文字相關處理模組,包括 string 、 re 、 difflib 、 textwrap unicodedata 、 stringprep 、 readline 、 rlcompleter 等。
Binary Data Services介紹二進位資料處理模組,包括 struct 、 codecs 等。
Data Types介紹各種處理資料的資料型態模組,包括 datetime 、 calendar 、 collections 、 collections.abc 、 heapq 、 bisect 、 array 、 weakref 、 types 、 copy 、 pprint 、 reprlib 、 enum 等。
Numeric and Mathematical Modules介紹處理數字資料的模組,包括 numbers 、 math 、 cmath 、 decimal 、 fractions 、 random 、 statistics 等。
Functional Programming Modules介紹函數式程式設計相關模組,包括 itertools 、 functools 、 operator 等。 File and Directory Access 介紹檔案及目錄處理的模組,包括 pathlib 、 os.path 、 fileinput 、 stat 、 filecmp 、 tempfile 、 glob 、 fnmatch 、 linecache 、 shutil 、 macpath 等。
Data Persistence介紹儲存資料相關模組,包括 pickle 、 copyreg 、 shelve 、 marshal 、 dbm 、 sqlite3 等。
Data Compression and Archiving介紹資料壓縮相關模組,包括 zlib 、 gzip 、 bz2 、 lzma 、 zipfile 、 tarfile 等。
File Formats介紹檔案格式相關模組,包括 csv 、 configparser 、 netrc 、 xdrlib 、 plistlib 等。
Cryptographic Services介紹密碼處理相關模組,包括 hashlib 、 hmac 、 secrets 等。
Generic Operating System Services介紹一般作業系統相關模組,包括 os 、 io 、 time 、 argparse 、 getopt 、 logging 、 logging.config 、 logging.handlers 、 getpass 、 curses 、 curses.textpad 、 curses.ascii 、 curses.panel 、 platform 、 errno 、 ctypes 等。
Concurrent Execution介紹並行計算相關模組,包括 threading 、 multiprocessing 、 concurrent 、 concurrent.futures 、 subprocess 、 sched 、 queue 、 dummy_threading 、 _thread 、 _dummy_thread 等。
Interprocess Communication and Networking介紹行程間通訊及網路處理相關模組,包括 socket 、 ssl 、 select 、 selectors 、 asyncio 、 asyncore 、 asynchat 、 signal 、 mmap 等。
Internet Data Handling介紹網路資料處理相關模組,包括 email 、 json 、 mailcap 、 mailbox 、 mimetypes 、 base64 、 binhex 、 binascii 、 quopri 、 uu 等。
Structured Markup Processing Tools介紹結構化標記處理工具,包括 html 、 html.parser 、 html.entities 、 xml.etree.ElementTree 、 xml.dom 、 xml.dom.minidom 、 xml.dom.pulldom 、 xml.sax 、 xml.sax.handler 、 xml.sax.saxutils 、 xml.sax.xmlreader 、 xml.parsers.expat 等。
Internet Protocols and Support介紹對網路協定的支援,包括 webbrowser 、 cgi 、 cgitb 、 wsgiref 、 urllib 、 urllib.request 、 urllib.response 、 urllib.parse 、 urllib.error 、 urllib.robotparser 、 http 、 http.client 、 ftplib 、 poplib 、 imaplib 、 nntplib 、 smtplib 、 smtpd 、 telnetlib 、 uuid 、 socketserver 、 http.server 、 http.cookies 、 http.cookiejar 、 xmlrpc 、 xmlrpc.client 、 xmlrpc.server 、 ipaddress 等。
Multimedia Services介紹多媒體相關模組,包括 audioop 、 aifc 、 sunau 、 wave 、 chunk 、 colorsys 、 imghdr 、 sndhdr 、 ossaudiodev 等。
Internationalization介紹國際化相關模組,包括 gettext 、 locale 等。
Program Frameworks介紹程式框架相關模組,包括 turtle 、 cmd 、 shlex 等。
Graphical User Interfaces with Tk介紹圖形應用的 Tk 模組,包括 tkinter 、 tkinter.ttk 、 tkinter.tix 、 tkinter.scrolledtext 等。
Development Tools介紹程式發展相關工具,包括 typing 、 pydoc 、 doctest 、 unittest 、 unittest.mock 、 unittest.mock 、 2to3 、 test 、 test.support 等。
Debugging and Profiling介紹除錯及效能分析相關模組,包括 bdb 、 faulthandler 、 pdb 、 cProfile 、 profile 、 timeit 、 trace 、 tracemalloc 等。
Software Packaging and Distribution介紹軟體套件及發佈相關工具,包括 distutils 、 ensurepip 、 venv 、 zipapp 等。
Python Runtime Services介紹執行期間相關服務,包括 sys 、 sysconfig 、 builtins 、 __main__ 、 warnings 、 contextlib 、 abc 、 atexit 、 traceback 、 __future__ 、 gc 、 inspect 、 site 、 fpectl 等。
Custom Python Interpreters介紹直譯器相關工具,包括 code 、 codeop 。
Importing Modules介紹引入模組相關工具,包括 zipimport 、 pkgutil 、 modulefinder 、 runpy 、 importlib 等。
Python Language Services介紹 Python 語言相關工具,包括 parser 、 ast 、 symtable 、 symbol 、 token 、 keyword 、 tokenize 、 tabnanny 、 pyclbr 、 py_compile 、 compileall 、 dis pickletools 等。
MS Windows Specific ServicesMS-Windows 特定服務,包括 msilib 、 msvcrt 、 winreg 、 winsound 。
Unix Specific ServicesUNIX 特定服務,包括 posix 、 pwd 、 spwd 、 grp 、 crypt 、 termios 、 tty 、 pty 、 fcntl 、 pipes 、 resource 、 nis 、 syslog 。

每個模組 (module) 都有為數不等的類別 (class)函數 (function) 、常數 (constant) 等定義,需要時可以直接用關鍵字 import 引入到自己的程式中使用。

例如 datetime 為處理時間、日期方面的模組,以下程式示範現在的時間日期

import datetime

now = datetime.datetime.now()
year = datetime.date.today().strftime("%Y")
month = datetime.date.today().strftime("%B")
wday = datetime.date.today().strftime("%A")

print("Current date and time: ", now)
print("Current year: ", year)
print("Month of the year: ", month)
print("Day of the week: ", wday)

#《程式語言教學誌》的範例程式
# http://kaiching.org/
# 檔名:library_demo.py
# 功能:示範 Python 的標準程式庫
# 作者:張凱慶 */

datetimedatetime 物件的 now() 方法回傳在地現在日期、時間的格式化字串, date 物件的 today() 回傳在地今日的日期物件, strftime() 方法回傳格式化日期字串。

執行結果如下

$ python library_demo
Current date and time: 2018-05-26 11:49:33.206263
Current year: 2018
Month of the year: May
Day of the week: Saturday
$

re正規運算式 (regular expression) 方面的模組正規運算式為依據規則表達的字串,大量運用在處理文字資料上,以下為正規運算式的簡單例子

import re

str = "There is no spoon."

v1 = re.sub(r"a""e", str)
v2 = re.sub(r"e""i", v1)
v3 = re.sub(r"i""o", v2)
v4 = re.sub(r"o""u", v3)
v5 = re.sub(r"u""a", v4)

print(v5)

#《程式語言教學誌》的範例程式
# http://kaiching.org/
# 檔名:library_demo2.py
# 功能:示範 Python 的標準程式庫
# 作者:張凱慶 */

re 中的 sub() 函數用來作字串 (string) 替換,此例將 str 中的所有母音字母都換成 a

執行結果如下

$ python library_demo2.py
Thara as na spaan.
$

另外像預設的浮點數 (floating-point number) 可能會有誤差,雖說誤差可能會僅是出現在小數點後第十九位,這對需要精確計算的時候就容易產生難以預期的影響,這時候使用 decimal 模組可以控制誤差的影響,例如

from decimal import *

print()
print(round(0.7 * 1.05, 2))
print(round(Decimal("0.7") * Decimal("1.05"), 2))
print()
print(1.00 % 0.10)
print(Decimal("1.00") % Decimal("0.10"))
print()
print(1 / 7)
print(Decimal("1") / Decimal("7"))
print()

#《程式語言教學誌》的範例程式
# http://kaiching.org/
# 檔名:library_demo3.py
# 功能:示範 Python 的標準程式庫
# 作者:張凱慶 */

執行結果如下

$ python
 
0.73
0.74
 
0.09999999999999995
0.00
 
0.14285714285714285
0.1428571428571428571428571429
 
$

有些誤差很小,有些誤差難以預期,如果使用標準程式庫decimal 就能控制誤差的問題了。

標準程式庫幾乎涵蓋各種應用,我們接下來要替 Encrypt 類別發展一個圖形介面 (graphical interface) ,就是用標準程式庫中的 tkinter 模組,這是跟 Tk 圖形介面程式庫連結的模組,讓使用者 (user) 可以輕鬆的編碼、解碼囉!

中英文術語對照
類別class
常數constant
浮點數floating-point number
函數function
圖形介面graphical interface
模組module
正規運算式regular expression
標準程式庫standard library
字串string
使用者user
重點整理
1. 標準程式庫具備各方面的應用,包括文字處理、二進位資料處理、數字及數學相關、函數程式設計、檔案及目錄存取等等。
2. datetime 為時間、日期方面的模組。
3. re 為正規運算式方面的模組。
4. decimal 模組可避免浮點數的誤差。
5. 標準程式庫在 GUI 方面整合 Tk ,模組名稱為 tkinter
問題與討論
1. 為什麼要有標準模組庫?難道不能把所有功能都直接內建嗎?
2. 為什麼預設的浮點數型態會有誤差?這誤差是怎麼造成的呢?
練習
1. 承接上一個單元的猜數字遊戲,將新程式寫在 guessgame.py 中,整合 find_number()ab_counter() 使之成為 GuessGame 類別的方法,注意參數的數量可能會有改變。
2. 承上題,繼續完成 GuessGame 類別,新增一個 run() 方法,將命令列的執行部分寫在 run() 裡。

相關教學影片

上一頁 單元 20 - 重構
回 Python 入門指南首頁
下一頁 GUI 篇
回 Python 教材首頁
回程式語言教材首頁