亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

direktori cari
Python是什么? Python 3 教程 Python3 基礎(chǔ)語(yǔ)法 編碼 Python3 基本數(shù)據(jù)類型 Python解釋器 Python 注釋 Python 數(shù)字運(yùn)算 Python 字符串 Python 列表 Python 編程第一步 Python 條件控制 Python 循環(huán) Python 函數(shù) Python 數(shù)據(jù)結(jié)構(gòu) Python 模塊 Python 輸入和輸出 Python 錯(cuò)誤和異常 Python 類 Python 標(biāo)準(zhǔn)庫(kù)概覽 Python Hello World 實(shí)例 Python 數(shù)字求和 Python 平方根 Python 二次方程 Python 計(jì)算三角形的面積 Python 隨機(jī)數(shù)生成 Python 攝氏溫度轉(zhuǎn)華氏溫度 Python 交換變量 Python if 語(yǔ)句 Python 判斷字符串是否為數(shù)字 Python 判斷奇數(shù)偶數(shù) Python 判斷閏年 Python 獲取最大值函數(shù) Python 質(zhì)數(shù)判斷 Python 階乘實(shí)例 Python 九九乘法表 Python 斐波那契數(shù)列 Python 阿姆斯特朗數(shù) Python 十進(jìn)制轉(zhuǎn)二進(jìn)制、八進(jìn)制、十六進(jìn)制 Python ASCII碼與字符相互轉(zhuǎn)換 Python 最大公約數(shù)算法 Python 最小公倍數(shù)算法 Python 簡(jiǎn)單計(jì)算器實(shí)現(xiàn) Python 生成日歷 Python 使用遞歸斐波那契數(shù)列 Python 文件 IO Python 字符串判斷 Python 字符串大小寫(xiě)轉(zhuǎn)換 Python 計(jì)算每個(gè)月天數(shù) Python 獲取昨天日期 Python list 常用操作 Python3 實(shí)例
watak

Python 標(biāo)準(zhǔn)庫(kù)概覽


操作系統(tǒng)接口

os模塊提供了不少與操作系統(tǒng)相關(guān)聯(lián)的函數(shù)。

>>> import os
>>> os.getcwd()      # 返回當(dāng)前的工作目錄
'C:\\Python34'
>>> os.chdir('/server/accesslogs')   # 修改當(dāng)前的工作目錄
>>> os.system('mkdir today')   # 執(zhí)行系統(tǒng)命令 mkdir 
0

建議使用 "import os" 風(fēng)格而非 "from os import *"。這樣可以保證隨操作系統(tǒng)不同而有所變化的 os.open() 不會(huì)覆蓋內(nèi)置函數(shù) open()。

在使用 os 這樣的大型模塊時(shí)內(nèi)置的 dir() 和 help() 函數(shù)非常有用:

>>> import os
>>> dir(os)
<returns a list of all module functions>
>>> help(os)
<returns an extensive manual page created from the module's docstrings>

針對(duì)日常的文件和目錄管理任務(wù),:mod:shutil 模塊提供了一個(gè)易于使用的高級(jí)接口:

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

文件通配符

glob模塊提供了一個(gè)函數(shù)用于從目錄通配符搜索中生成文件列表:

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

命令行參數(shù)

通用工具腳本經(jīng)常調(diào)用命令行參數(shù)。這些命令行參數(shù)以鏈表形式存儲(chǔ)于 sys 模塊的 argv 變量。例如在命令行中執(zhí)行 "python demo.py one two three" 后可以得到以下輸出結(jié)果:

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

錯(cuò)誤輸出重定向和程序終止

sys 還有 stdin,stdout 和 stderr 屬性,即使在 stdout 被重定向時(shí),后者也可以用于顯示警告和錯(cuò)誤信息。

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

大多腳本的定向終止都使用 "sys.exit()"。


字符串正則匹配

re模塊為高級(jí)字符串處理提供了正則表達(dá)式工具。對(duì)于復(fù)雜的匹配和處理,正則表達(dá)式提供了簡(jiǎn)潔、優(yōu)化的解決方案:

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

如果只需要簡(jiǎn)單的功能,應(yīng)該首先考慮字符串方法,因?yàn)樗鼈兎浅:?jiǎn)單,易于閱讀和調(diào)試:

>>> 'tea for too'.replace('too', 'two')
'tea for two'

數(shù)學(xué)

math模塊為浮點(diǎn)運(yùn)算提供了對(duì)底層C函數(shù)庫(kù)的訪問(wèn):

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

random提供了生成隨機(jī)數(shù)的工具。

>>> import random
>>> random.choice(['apple', 'pear', 'banana'])
'apple'
>>> random.sample(range(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èn) 互聯(lián)網(wǎng)

有幾個(gè)模塊用于訪問(wèn)互聯(lián)網(wǎng)以及處理網(wǎng)絡(luò)通信協(xié)議。其中最簡(jiǎn)單的兩個(gè)是用于處理從 urls 接收的數(shù)據(jù)的 urllib.request 以及用于發(fā)送電子郵件的 smtplib:

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

注意第二個(gè)例子需要本地有一個(gè)在運(yùn)行的郵件服務(wù)器。


日期和時(shí)間

datetime模塊為日期和時(shí)間處理同時(shí)提供了簡(jiǎn)單和復(fù)雜的方法。

支持日期和時(shí)間算法的同時(shí),實(shí)現(xiàn)的重點(diǎn)放在更有效的處理和格式化輸出。

該模塊還支持時(shí)區(qū)處理:

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

性能度量

有些用戶對(duì)了解解決同一問(wèn)題的不同方法之間的性能差異很感興趣。Python 提供了一個(gè)度量工具,為這些問(wèn)題提供了直接答案。

例如,使用元組封裝和拆封來(lái)交換元素看起來(lái)要比使用傳統(tǒng)的方法要誘人的多,timeit 證明了現(xiàn)代的方法更快一些。

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

相對(duì)于 timeit 的細(xì)粒度,:mod:profile 和 pstats 模塊提供了針對(duì)更大代碼塊的時(shí)間度量工具。


測(cè)試模塊

開(kāi)發(fā)高質(zhì)量軟件的方法之一是為每一個(gè)函數(shù)開(kāi)發(fā)測(cè)試代碼,并且在開(kāi)發(fā)過(guò)程中經(jīng)常進(jìn)行測(cè)試

doctest模塊提供了一個(gè)工具,掃描模塊并根據(jù)程序中內(nèi)嵌的文檔字符串執(zhí)行測(cè)試。

測(cè)試構(gòu)造如同簡(jiǎn)單的將它的輸出結(jié)果剪切并粘貼到文檔字符串中。

通過(guò)用戶提供的例子,它強(qiáng)化了文檔,允許 doctest 模塊確認(rèn)代碼的結(jié)果是否與文檔一致:

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()   # 自動(dòng)驗(yàn)證嵌入測(cè)試

unittest模塊不像 doctest模塊那么容易使用,不過(guò)它可以在一個(gè)獨(dú)立的文件里提供一個(gè)更全面的測(cè)試集:

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)
        self.assertRaises(ZeroDivisionError, average, [])
        self.assertRaises(TypeError, average, 20, 30, 70)

unittest.main() # Calling from the command line invokes all tests
Artikel sebelumnya: Artikel seterusnya: