Python標(biāo)準(zhǔn)庫(kù)學(xué)習(xí)筆記

操作系統(tǒng)接口

通過(guò)導(dǎo)入:

import os

比較有用的方法為:

os.system('shell command')

調(diào)用了shell命令

此外拒垃,dir()help()將幫助學(xué)習(xí)模塊的方法华蜒。

跟文件有關(guān)的操作需要導(dǎo)入:

>>> import shutil
>>> shutil.copyfile('data.db', 'archive.db')
>>> shutil.move('/build/executables', 'installdir')

文件通配符號(hào)

glob模塊提供文件查找的功能渠缕。

>>> import glob
>>> glob.glob('*.py')
['primes.py', 'random.py', 'quote.py']

操作系統(tǒng)參數(shù)

通過(guò)導(dǎo)入:

import sys

>>> import sys
>>> print sys.argv
['demo.py', 'one', 'two', 'three']

標(biāo)準(zhǔn)錯(cuò)誤輸出

>>> sys.stderr.write('Warning, log file not found starting a new one\n')
Warning, log file not found starting a new one

The most direct way to terminate a script is to use sys.exit().

字符串模式匹配

通過(guò)導(dǎo)入:

import 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'

#just string methos
>>> 'tea for too'.replace('too', 'two')
'tea for two'

數(shù)學(xué)相關(guān)

很簡(jiǎn)單:

>>> import math
>>> math.cos(math.pi / 4.0)
0.70710678118654757
>>> math.log(1024, 2)
10.0

>>> import random
>>> random.choice(['apple', 'pear', 'banana'])
'apple'
>>> random.sample(xrange(100), 10)   # sampling without replacement
[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]
>>> random.random()    # random float
0.17970987693706186
>>> random.randrange(6)    # random integer chosen from range(6)
4

網(wǎng)絡(luò)讀取


>>> import urllib2
>>> for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'):
    ...     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()

日期和時(shí)間

>>> # 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ù)壓縮

>>> import zlib
>>> s = 'witch which has which witches wrist watch'
>>> len(s)
41
>>> t = zlib.compress(s)
>>> len(t)
37
>>> zlib.decompress(t)
'witch which has which witches wrist watch'
>>> zlib.crc32(s)
226805979

性能測(cè)量

>>> 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

質(zhì)量控制-也就是QC

def average(values):
        """Computes the arithmetic mean of a list of numbers.

            >>> print average([20, 30, 70])
                40.0
                    """
                        return sum(values, 0.0) / len(values)

                    import doctest
                    doctest.testmod()   # automatically validate the embedded tests

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

輸出格式化

>>> import repr
>>> repr.repr(set('supercalifragilisticexpialidocious'))
"set(['a', 'c', 'd', 'e', 'f', 'g', ...])"

>>> import pprint
>>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',
                                                            ...     'yellow'], 'blue']]]
...
>>> pprint.pprint(t, width=30)
[[[['black', 'cyan'],
      'white',
      ['green', 'red']],
    [['magenta', 'yellow'],
        'blue']]]


>>> import textwrap
>>> doc = """The wrap() method is just like fill() except that it returns
... a list of strings instead of one big string with newlines to separate
... the wrapped lines."""
...
>>> print textwrap.fill(doc, width=40)
The wrap() method is just like fill()
except that it returns a list of strings
instead of one big string with newlines
to separate the wrapped lines.

模板

字符串提供了一個(gè)通用的模板類,可以在使用的才確定字符串內(nèi)的內(nèi)容。

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

>>> t = Template('Return the $item to $owner.')
>>> d = dict(item='unladen swallow')
>>> t.substitute(d)
Traceback (most recent call last):
    ...
KeyError: 'owner'
>>> t.safe_substitute(d)
'Return the unladen swallow to $owner.'

二進(jìn)制數(shù)據(jù)記錄布局的工作

看這個(gè)例子:

import struct

data = open('myfile.zip', 'rb').read()
start = 0
for i in range(3):                      # show the first 3 file headers
    start += 14
        fields = struct.unpack('<IIIHH', data[start:start+16])
            crc32, comp_size, uncomp_size, filenamesize, extra_size = fields

                start += 16
                    filename = data[start:start+filenamesize]
                        start += filenamesize
                            extra = data[start:start+extra_size]
                                print filename, hex(crc32), comp_size, uncomp_size

                                    start += extra_size + comp_size     # skip to the next header

多線程

import threading, zipfile

class AsyncZip(threading.Thread):
        def __init__(self, infile, outfile):
                    threading.Thread.__init__(self)
                            self.infile = infile
                                    self.outfile = outfile
                                        def run(self):
                                                    f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
                                                            f.write(self.infile)
                                                                    f.close()
                                                                            print 'Finished background zip of: ', self.infile

                                                                            background = AsyncZip('mydata.txt', 'myarchive.zip')
                                                                            background.start()
                                                                            print 'The main program continues to run in foreground.'

                                                                            background.join()    # Wait for the background task to finish
                                                                            print 'Main program waited until background was done.'

日志相關(guān)

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

弱引用

>>> 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:/python26/lib/weakref.py", line 46, in __getitem__
                            o = self.data[key]()
                            KeyError: 'primary'

針對(duì)list的工作工具

比如說(shuō):
array
connection
biset
heapq

分別舉例:

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

>>> from collections import deque
>>> d = deque(["task1", "task2", "task3"])
>>> d.append("task4")
>>> print "Handling", d.popleft()
Handling task1

unsearched = deque([starting_node])
def breadth_first_search(unsearched):
        node = unsearched.popleft()
            for m in gen_moves(node):
                        if is_goal(m):
                                        return m
                                            unsearched.append(m)

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

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

十進(jìn)制浮點(diǎn)數(shù)運(yùn)算

>>> from decimal import *
>>> x = Decimal('0.70') * Decimal('1.05')
>>> x
Decimal('0.7350')
>>> x.quantize(Decimal('0.01'))  # round to nearest cent
Decimal('0.74')
>>> round(.70 * 1.05, 2)         # same calculation with floats
0.73

>>> Decimal('1.00') % Decimal('.10')
Decimal('0.00')
>>> 1.00 % 0.10
0.09999999999999995

>>> sum([Decimal('0.1')]*10) == Decimal('1.0')
True
>>> sum([0.1]*10) == 1.0
False

>>> getcontext().prec = 36
>>> Decimal(1) / Decimal(7)
Decimal('0.142857142857142857142857142857142857')
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市麻蹋,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌焊切,老刑警劉巖扮授,帶你破解...
    沈念sama閱讀 212,332評(píng)論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異专肪,居然都是意外死亡刹勃,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,508評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門(mén)嚎尤,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)荔仁,“玉大人,你說(shuō)我怎么就攤上這事芽死》α海” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 157,812評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵关贵,是天一觀的道長(zhǎng)遇骑。 經(jīng)常有香客問(wèn)我,道長(zhǎng)揖曾,這世上最難降的妖魔是什么落萎? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 56,607評(píng)論 1 284
  • 正文 為了忘掉前任亥啦,我火速辦了婚禮,結(jié)果婚禮上练链,老公的妹妹穿的比我還像新娘翔脱。我一直安慰自己,他們只是感情好兑宇,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,728評(píng)論 6 386
  • 文/花漫 我一把揭開(kāi)白布碍侦。 她就那樣靜靜地躺著,像睡著了一般隶糕。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上站玄,一...
    開(kāi)封第一講書(shū)人閱讀 49,919評(píng)論 1 290
  • 那天枚驻,我揣著相機(jī)與錄音,去河邊找鬼株旷。 笑死再登,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的晾剖。 我是一名探鬼主播锉矢,決...
    沈念sama閱讀 39,071評(píng)論 3 410
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼齿尽!你這毒婦竟也來(lái)了沽损?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 37,802評(píng)論 0 268
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤循头,失蹤者是張志新(化名)和其女友劉穎绵估,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體卡骂,經(jīng)...
    沈念sama閱讀 44,256評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡国裳,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,576評(píng)論 2 327
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了全跨。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片缝左。...
    茶點(diǎn)故事閱讀 38,712評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖浓若,靈堂內(nèi)的尸體忽然破棺而出渺杉,到底是詐尸還是另有隱情,我是刑警寧澤七嫌,帶...
    沈念sama閱讀 34,389評(píng)論 4 332
  • 正文 年R本政府宣布少办,位于F島的核電站,受9級(jí)特大地震影響诵原,放射性物質(zhì)發(fā)生泄漏英妓。R本人自食惡果不足惜挽放,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,032評(píng)論 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望蔓纠。 院中可真熱鬧辑畦,春花似錦、人聲如沸腿倚。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,798評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)敷燎。三九已至暂筝,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間硬贯,已是汗流浹背焕襟。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,026評(píng)論 1 266
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留饭豹,地道東北人鸵赖。 一個(gè)月前我還...
    沈念sama閱讀 46,473評(píng)論 2 360
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像拄衰,于是被迫代替她去往敵國(guó)和親它褪。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,606評(píng)論 2 350

推薦閱讀更多精彩內(nèi)容