日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:11.標(biāo)準(zhǔn)庫簡介——第二部分

11. 標(biāo)準(zhǔn)庫簡介 —— 第二部分

第二部分涵蓋了專業(yè)編程所需要的更高級的模塊。這些模塊很少用在小腳本中。

在京山等地區(qū),都構(gòu)建了全面的區(qū)域性戰(zhàn)略布局,加強(qiáng)發(fā)展的系統(tǒng)性、市場前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務(wù)理念,為客戶提供成都網(wǎng)站制作、成都網(wǎng)站建設(shè) 網(wǎng)站設(shè)計制作按需定制設(shè)計,公司網(wǎng)站建設(shè),企業(yè)網(wǎng)站建設(shè),高端網(wǎng)站設(shè)計,全網(wǎng)整合營銷推廣,成都外貿(mào)網(wǎng)站建設(shè)公司,京山網(wǎng)站建設(shè)費用合理。

11.1. 格式化輸出

reprlib 模塊提供了一個定制化版本的 repr() 函數(shù),用于縮略顯示大型或深層嵌套的容器對象:

 
 
 
 
  1. >>> import reprlib
  2. >>> reprlib.repr(set('supercalifragilisticexpialidocious'))
  3. "{'a', 'c', 'd', 'e', 'f', 'g', ...}"

pprint 模塊提供了更加復(fù)雜的打印控制,其輸出的內(nèi)置對象和用戶自定義對象能夠被解釋器直接讀取。當(dāng)輸出結(jié)果過長而需要折行時,“美化輸出機(jī)制”會添加換行符和縮進(jìn),以更清楚地展示數(shù)據(jù)結(jié)構(gòu):

 
 
 
 
  1. >>> import pprint
  2. >>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',
  3. ... 'yellow'], 'blue']]]
  4. ...
  5. >>> pprint.pprint(t, width=30)
  6. [[[['black', 'cyan'],
  7. 'white',
  8. ['green', 'red']],
  9. [['magenta', 'yellow'],
  10. 'blue']]]

textwrap 模塊能夠格式化文本段落,以適應(yīng)給定的屏幕寬度:

 
 
 
 
  1. >>> import textwrap
  2. >>> doc = """The wrap() method is just like fill() except that it returns
  3. ... a list of strings instead of one big string with newlines to separate
  4. ... the wrapped lines."""
  5. ...
  6. >>> print(textwrap.fill(doc, width=40))
  7. The wrap() method is just like fill()
  8. except that it returns a list of strings
  9. instead of one big string with newlines
  10. to separate the wrapped lines.

locale 模塊處理與特定地域文化相關(guān)的數(shù)據(jù)格式。locale 模塊的 format 函數(shù)包含一個 grouping 屬性,可直接將數(shù)字格式化為帶有組分隔符的樣式:

 
 
 
 
  1. >>> import locale
  2. >>> locale.setlocale(locale.LC_ALL, 'English_United States.1252')
  3. 'English_United States.1252'
  4. >>> conv = locale.localeconv() # get a mapping of conventions
  5. >>> x = 1234567.8
  6. >>> locale.format("%d", x, grouping=True)
  7. '1,234,567'
  8. >>> locale.format_string("%s%.*f", (conv['currency_symbol'],
  9. ... conv['frac_digits'], x), grouping=True)
  10. '$1,234,567.80'

11.2. 模板

string 模塊包含一個通用的 Template 類,具有適用于最終用戶的簡化語法。它允許用戶在不更改應(yīng)用邏輯的情況下定制自己的應(yīng)用。

上述格式化操作是通過占位符實現(xiàn)的,占位符由 $ 加上合法的 python 標(biāo)識符(只能包含字母、數(shù)字和下劃線)構(gòu)成。一旦使用花括號將占位符括起來,就可以在后面直接跟上更多的字母和數(shù)字而無需空格分割。$$ 將被轉(zhuǎn)義成單個字符 $:

 
 
 
 
  1. >>> from string import Template
  2. >>> t = Template('${village}folk send $$10 to $cause.')
  3. >>> t.substitute(village='Nottingham', cause='the ditch fund')
  4. 'Nottinghamfolk send $10 to the ditch fund.'

如果在字典或關(guān)鍵字參數(shù)中未提供某個占位符的值,那么 substitute() 方法將拋出 KeyError。對于郵件合并類型的應(yīng)用,用戶提供的數(shù)據(jù)有可能是不完整的,此時使用 safe_substitute() 方法更加合適 —— 如果數(shù)據(jù)缺失,它會直接將占位符原樣保留。

 
 
 
 
  1. >>> t = Template('Return the $item to $owner.')
  2. >>> d = dict(item='unladen swallow')
  3. >>> t.substitute(d)
  4. Traceback (most recent call last):
  5. ...
  6. KeyError: 'owner'
  7. >>> t.safe_substitute(d)
  8. 'Return the unladen swallow to $owner.'

Template 的子類可以自定義分隔符。例如,以下是某個照片瀏覽器的批量重命名功能,采用了百分號作為日期、照片序號和照片格式的占位符:

 
 
 
 
  1. >>> import time, os.path
  2. >>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg']
  3. >>> class BatchRename(Template):
  4. ... delimiter = '%'
  5. ...
  6. >>> fmt = input('Enter rename style (%d-date %n-seqnum %f-format): ')
  7. Enter rename style (%d-date %n-seqnum %f-format): Ashley_%n%f
  8. >>> t = BatchRename(fmt)
  9. >>> date = time.strftime('%d%b%y')
  10. >>> for i, filename in enumerate(photofiles):
  11. ... base, ext = os.path.splitext(filename)
  12. ... newname = t.substitute(d=date, n=i, f=ext)
  13. ... print('{0} --> {1}'.format(filename, newname))
  14. img_1074.jpg --> Ashley_0.jpg
  15. img_1076.jpg --> Ashley_1.jpg
  16. img_1077.jpg --> Ashley_2.jpg

模板的另一個應(yīng)用是將程序邏輯與多樣的格式化輸出細(xì)節(jié)分離開來。這使得對 XML 文件、純文本報表和 HTML 網(wǎng)絡(luò)報表使用自定義模板成為可能。

11.3. 使用二進(jìn)制數(shù)據(jù)記錄格式

struct 模塊提供了 pack() 和 unpack() 函數(shù),用于處理不定長度的二進(jìn)制記錄格式。下面的例子展示了在不使用 zipfile 模塊的情況下,如何循環(huán)遍歷一個 ZIP 文件的所有頭信息。Pack 代碼 "H""I" 分別代表兩字節(jié)和四字節(jié)無符號整數(shù)。"<" 代表它們是標(biāo)準(zhǔn)尺寸的小端字節(jié)序:

 
 
 
 
  1. import struct
  2. with open('myfile.zip', 'rb') as f:
  3. data = f.read()
  4. start = 0
  5. for i in range(3): # show the first 3 file headers
  6. start += 14
  7. fields = struct.unpack('
  8. crc32, comp_size, uncomp_size, filenamesize, extra_size = fields
  9. start += 16
  10. filename = data[start:start+filenamesize]
  11. start += filenamesize
  12. extra = data[start:start+extra_size]
  13. print(filename, hex(crc32), comp_size, uncomp_size)
  14. start += extra_size + comp_size # skip to the next header

11.4. 多線程

線程是一種對于非順序依賴的多個任務(wù)進(jìn)行解耦的技術(shù)。多線程可以提高應(yīng)用的響應(yīng)效率,當(dāng)接收用戶輸入的同時,保持其他任務(wù)在后臺運行。一個有關(guān)的應(yīng)用場景是,將 I/O 和計算運行在兩個并行的線程中。

以下代碼展示了高階的 threading 模塊如何在后臺運行任務(wù),且不影響主程序的繼續(xù)運行:

 
 
 
 
  1. import threading, zipfile
  2. class AsyncZip(threading.Thread):
  3. def __init__(self, infile, outfile):
  4. threading.Thread.__init__(self)
  5. self.infile = infile
  6. self.outfile = outfile
  7. def run(self):
  8. f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
  9. f.write(self.infile)
  10. f.close()
  11. print('Finished background zip of:', self.infile)
  12. background = AsyncZip('mydata.txt', 'myarchive.zip')
  13. background.start()
  14. print('The main program continues to run in foreground.')
  15. background.join() # Wait for the background task to finish
  16. print('Main program waited until background was done.')

多線程應(yīng)用面臨的主要挑戰(zhàn)是,相互協(xié)調(diào)的多個線程之間需要共享數(shù)據(jù)或其他資源。為此,threading 模塊提供了多個同步操作原語,包括線程鎖、事件、條件變量和信號量。

盡管這些工具非常強(qiáng)大,但微小的設(shè)計錯誤卻可以導(dǎo)致一些難以復(fù)現(xiàn)的問題。因此,實現(xiàn)多任務(wù)協(xié)作的首選方法是將所有對資源的請求集中到一個線程中,然后使用 queue 模塊向該線程供應(yīng)來自其他線程的請求。 應(yīng)用程序使用 Queue 對象進(jìn)行線程間通信和協(xié)調(diào),更易于設(shè)計,更易讀,更可靠。

11.5. 日志記錄

logging 模塊提供功能齊全且靈活的日志記錄系統(tǒng)。在最簡單的情況下,日志消息被發(fā)送到文件或 sys.stderr

 
 
 
 
  1. import logging
  2. logging.debug('Debugging information')
  3. logging.info('Informational message')
  4. logging.warning('Warning:config file %s not found', 'server.conf')
  5. logging.error('Error occurred')
  6. logging.critical('Critical error -- shutting down')

這會產(chǎn)生以下輸出:

 
 
 
 
  1. WARNING:root:Warning:config file server.conf not found
  2. ERROR:root:Error occurred
  3. CRITICAL:root:Critical error -- shutting down

默認(rèn)情況下,informational 和 debugging 消息被壓制,輸出會發(fā)送到標(biāo)準(zhǔn)錯誤流。其他輸出選項包括將消息轉(zhuǎn)發(fā)到電子郵件,數(shù)據(jù)報,套接字或 HTTP 服務(wù)器。新的過濾器可以根據(jù)消息優(yōu)先級選擇不同的路由方式:DEBUG,INFOWARNING,ERROR,和 CRITICAL。

日志系統(tǒng)可以直接從 Python 配置,也可以從用戶配置文件加載,以便自定義日志記錄而無需更改應(yīng)用程序。

11.6. 弱引用

Python 會自動進(jìn)行內(nèi)存管理(對大多數(shù)對象進(jìn)行引用計數(shù)并使用 garbage collection 來清除循環(huán)引用)。 當(dāng)某個對象的最后一個引用被移除后不久就會釋放其所占用的內(nèi)存。

此方式對大多數(shù)應(yīng)用來說都適用,但偶爾也必須在對象持續(xù)被其他對象所使用時跟蹤它們。 不幸的是,跟蹤它們將創(chuàng)建一個會令其永久化的引用。 weakref 模塊提供的工具可以不必創(chuàng)建引用就能跟蹤對象。 當(dāng)對象不再需要時,它將自動從一個弱引用表中被移除,并為弱引用對象觸發(fā)一個回調(diào)。 典型應(yīng)用包括對創(chuàng)建開銷較大的對象進(jìn)行緩存:

 
 
 
 
  1. >>> import weakref, gc
  2. >>> class A:
  3. ... def __init__(self, value):
  4. ... self.value = value
  5. ... def __repr__(self):
  6. ... return str(self.value)
  7. ...
  8. >>> a = A(10) # create a reference
  9. >>> d = weakref.WeakValueDictionary()
  10. >>> d['primary'] = a # does not create a reference
  11. >>> d['primary'] # fetch the object if it is still alive
  12. 10
  13. >>> del a # remove the one reference
  14. >>> gc.collect() # run garbage collection right away
  15. 0
  16. >>> d['primary'] # entry was automatically removed
  17. Traceback (most recent call last):
  18. File "", line 1, in
  19. d['primary'] # entry was automatically removed
  20. File "C:/Python311/lib/weakref.py", line 46, in __getitem__
  21. o = self.data[key]()
  22. KeyError: 'primary'

11.7. 用于操作列表的工具

許多對于數(shù)據(jù)結(jié)構(gòu)的需求可以通過內(nèi)置列表類型來滿足。 但是,有時也會需要具有不同效費比的替代實現(xiàn)。

array 模塊提供了一種 array() 對象,它類似于列表,但只能存儲類型一致的數(shù)據(jù)且存儲密集更高。 下面的例子演示了一個以兩個字節(jié)為存儲單元的無符號二進(jìn)制數(shù)值的數(shù)組 (類型碼為 "H"),而對于普通列表來說,每個條目存儲為標(biāo)準(zhǔn) Python 的 int 對象通常要占用16 個字節(jié):

 
 
 
 
  1. >>> from array import array
  2. >>> a = array('H', [4000, 10, 700, 22222])
  3. >>> sum(a)
  4. 26932
  5. >>> a[1:3]
  6. array('H', [10, 700])

collections 模塊提供了一種 deque() 對象,它類似于列表,但從左端添加和彈出的速度較快,而在中間查找的速度較慢。 此種對象適用于實現(xiàn)隊列和廣度優(yōu)先樹搜索:

 
 
 
 
  1. >>> from collections import deque
  2. >>> d = deque(["task1", "task2", "task3"])
  3. >>> d.append("task4")
  4. >>> print("Handling", d.popleft())
  5. Handling task1
 
 
 
 
  1. unsearched = deque([starting_node])
  2. def breadth_first_search(unsearched):
  3. node = unsearched.popleft()
  4. for m in gen_moves(node):
  5. if is_goal(m):
  6. return m
  7. unsearched.append(m)

在替代的列表實現(xiàn)以外,標(biāo)準(zhǔn)庫也提供了其他工具,例如 bisect 模塊具有用于操作有序列表的函數(shù):

 
 
 
 
  1. >>> import bisect
  2. >>> scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')]
  3. >>> bisect.insort(scores, (300, 'ruby'))
  4. >>> scores
  5. [(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]

heapq 模塊提供了基于常規(guī)列表來實現(xiàn)堆的函數(shù)。 最小值的條目總是保持在位置零。 這對于需要重復(fù)訪問最小元素而不希望運行完整列表排序的應(yīng)用來說非常有用:

 
 
 
 
  1. >>> from heapq import heapify, heappop, heappush
  2. >>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
  3. >>> heapify(data) # rearrange the list into heap order
  4. >>> heappush(data, -5) # add a new entry
  5. >>> [heappop(data) for i in range(3)] # fetch the three smallest entries
  6. [-5, 0, 1]

11.8. 十進(jìn)制浮點運算

decimal 模塊提供了一種 Decimal 數(shù)據(jù)類型用于十進(jìn)制浮點運算。 相比內(nèi)置的 float 二進(jìn)制浮點實現(xiàn),該類特別適用于

  • 財務(wù)應(yīng)用和其他需要精確十進(jìn)制表示的用途,

  • 控制精度,

  • 控制四舍五入以滿足法律或監(jiān)管要求,

  • 跟蹤有效小數(shù)位,或

  • 用戶期望結(jié)果與手工完成的計算相匹配的應(yīng)用程序。

例如,使用十進(jìn)制浮點和二進(jìn)制浮點數(shù)計算70美分手機(jī)和5%稅的總費用,會產(chǎn)生的不同結(jié)果。如果結(jié)果四舍五入到最接近的分?jǐn)?shù)差異會更大:

 
 
 
 
  1. >>> from decimal import *
  2. >>> round(Decimal('0.70') * Decimal('1.05'), 2)
  3. Decimal('0.74')
  4. >>> round(.70 * 1.05, 2)
  5. 0.73

Decimal 表示的結(jié)果會保留尾部的零,并根據(jù)具有兩個有效位的被乘數(shù)自動推出四個有效位。 Decimal 可以模擬手工運算來避免當(dāng)二進(jìn)制浮點數(shù)無法精確表示十進(jìn)制數(shù)時會導(dǎo)致的問題。

精確表示特性使得 Decimal 類能夠執(zhí)行對于二進(jìn)制浮點數(shù)來說不適用的模運算和相等性檢測:

 
 
 
 
  1. >>> Decimal('1.00') % Decimal('.10')
  2. Decimal('0.00')
  3. >>> 1.00 % 0.10
  4. 0.09999999999999995
  5. >>> sum([Decimal('0.1')]*10) == Decimal('1.0')
  6. True
  7. >>> sum([0.1]*10) == 1.0
  8. False

decimal 模塊提供了運算所需要的足夠精度:

 
 
 
 
  1. >>> getcontext().prec = 36
  2. >>> Decimal(1) / Decimal(7)
  3. Decimal('0.142857142857142857142857142857142857')

分享題目:創(chuàng)新互聯(lián)Python教程:11.標(biāo)準(zhǔn)庫簡介——第二部分
文章出自:http://m.5511xx.com/article/dpcpgoo.html