模塊就是程序python
任何python程序均可以做爲模塊導入
1 >>> import sys 2 >>> sys.path.append('/opt/python/') 3 >>> import hello 4 hello, world!
模塊是用來定義的linux
#hello2.py正則表達式
def hello():shell
print("hello, world!") 數據庫
1 >>> import hello2 2 >>> hello2.hello() 3 hello, world!
2. 在模塊中添加測試代碼json
在主程序中(包括解釋器的交互式提示符),變量__name__的值是'__main__',而再倒入的模塊中,這個變量被設置爲該模塊的名稱
1 >>> __name__ 2 '__main__' 3 >>> hello2.__name__ 4 'hello2'
#hello3.py api
一個包含有條件的執行的測試代碼的模塊,若是將這個模塊做爲程序運行,將執行函數hello;若是導入它,其行爲將像普通模塊同樣。
1 def hello(): 2 print("hello, world!") 3 4 def test(): 5 hello() 6 7 if __name__ == '__main__': test()
執行結果
讓模塊可用app
1 >>> import sys, pprint 2 >>> pprint.pprint(sys.path) 3 ['', 4 '/usr/local/python3.5/lib/python35.zip', 5 '/usr/local/python3.5/lib/python3.5', 6 '/usr/local/python3.5/lib/python3.5/plat-linux', 7 '/usr/local/python3.5/lib/python3.5/lib-dynload', 8 '/usr/local/python3.5/lib/python3.5/site-packages', 9 '/opt/python/', 10 '/opt/python/', 11 '/opt/python/', 12 '/opt/python/', 13 '/opt/python/']
2. 包dom
爲組織模塊,可將其編組爲包。包其實就是另外一種模塊,但他們能夠包含其餘模塊。模塊存儲在擴展名爲.py的文件中,而包則是一個目錄。要被python視爲包,目錄必須包含文件__init__.py。若是像普通模塊同樣導入包,文件__init__.py的內容就將是包的內容。要將模塊加入包中,只需將模塊文件放在包目錄中便可。你還能夠在包中嵌套其餘包。例如,要建立一個名爲drawing的包,其中包含模塊shapes和colors.ide
一種簡單的包佈局
文件目錄 描述
~/python/ PYTHONPATH中的目錄
~/python/drawing/ 包目錄(包drawing)
~/python/drawing/__init__.py 包代碼(模塊drawing)
~/python/drawing/colors.py 模塊colosr
~/python/drawing/shapes.py 模塊shapes
import drawing 導入drawing包
import drawing.colors 導入drawing包中的模塊colors
from drawing import shapes 導入模塊shapes
模塊中包含什麼
1.使用dir
要查明模塊包含哪些東西,可以使用函數dir,它列出對象的全部屬性(對於模塊,它列出全部的函數、類,變量等)。若是將dir(copy)的結果打印出來,將是一個很長的名稱列表
1 >>> import copy 2 >>> [n for n in dir(copy) if not n.startswith('_')] 3 ['Error', 'PyStringMap', 'builtins', 'copy', 'deepcopy', 'dispatch_table', 'error', 'name', 't', 'weakref']
2.變量__all__
這個變量包含一個列表,它與前面使用列表推導建立的列表相似,可是在模塊內部設置的
1 >>> copy.__all__ 2 ['Error', 'copy', 'deepcopy']
文檔
這樣就得到了函數range的準確描述
1 >>> print(range.__doc__) 2 range(stop) -> range object 3 range(start, stop[, step]) -> range object 4 5 Return an object that produces a sequence of integers from start (inclusive) 6 to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1. 7 start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3. 8 These are exactly the valid indices for a list of 4 elements. 9 When step is given, it specifies the increment (or decrement).
使用源代碼
1 >>> print(copy.__file__) 2 /usr/local/python3.5/lib/python3.5/copy.py
sys
模塊sys能訪問與python解釋器緊密相關的變量和函數
模塊sys中一些重要的函數和變量
函數/變量 描述
argv 命令行參數,包括腳本名
exit([arg]) 退出當前程序,可經過可選參數指定返回值或錯誤消息
modules 一個字典,將模塊名稱映射到加載的模塊
path 一個列表,包含要在其中查找模塊的目錄名稱
platform 一個平臺標識符,如sunos5或win32
stdin 標準輸入流——一個相似於文件的對象
stdout 標準輸出流——一個相似於文件的對象
stderr 標準錯誤流——一個相似於文件的對象
os
模塊os讓你可以訪問多個操做系統服務,os及其子模塊os.path還包含多個查看、建立和刪除目錄及文件的函數,以及一些操做路徑的函數
模塊os中的一些重要的函數和變量
函數/變量 描述
environ 包含環境變量的映射
system(command) 在子shell中執行操做系統命令
sep 路徑中使用的分隔符
pathsep 分隔不一樣路徑的分隔符
linesep 行爲分隔符('\n'、'\r'或'\r\n')
urandom(n) 返回n個字節的強加密隨機數據
fileinput
模塊fileinput中一些重要的函數
函數 描述
input([files[, inplace[, backup]]]) 幫助迭代多個輸入流中的行
filename() 返回當前文件的名稱
lineno() 返回(累計的)當前行號
filelineno() 返回在當前文件中的行號
isfirstline() 檢查當前行是不是文件中的第一行
isstdin() 檢查最後一行是否來自sys.stdin
nextfile() 關閉當前文件並移到下一個文件
close() 關閉序列
#11.py
1 import fileinput 2 3 for line in fileinput.input(inplace=True): 4 line = line.rstrip() 5 num = fileinput.lineno() 6 print('{:<50} # {:2d}'.format(line, num))
若是像下面這樣執行程序,並將其做爲參數傳入:
# python 11.py 11.py
執行結果
#!/usr/bin/env python # 1 #-*- coding:utf-8 -*- # 2 import fileinput # 3 # 4 for line in fileinput.input(inplace=True): # 5 line = line.rstrip() # 6 num = fileinput.lineno() # 7 print('{:<50} # {:2d}'.format(line, num)) # 8
集合
在較新的版本中,集合是有內置類set實現的,這意味着你能夠直接建立集合,而無需導入模塊sets
1 >>> set(range(10)) 2 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
可以使用序列(或其餘可迭代對象)來建立集合,也可以使用花括號顯示的指定。不能僅使用花括號來建立空集合,由於這將建立一個空字典。
1 >>> type({}) 2 <class 'dict'>
要計算連個集合的並集,可對其中一個集合調用方法union,也可以使用按位或運算符|
1 >>> a = {1, 2, 3} 2 >>> b = {2, 3, 4} 3 >>> a.union(b) 4 {1, 2, 3, 4} 5 >>> a | b 6 {1, 2, 3, 4}
1 >>> c = a & b 2 >>> c.issubset(a) 3 True 4 >>> c <= a 5 True 6 >>> c.issuperset(a) 7 False 8 >>> c >= a 9 False 10 >>> a.intersection(b) 11 {2, 3} 12 >>> a & b 13 {2, 3} 14 >>> a.difference(b) 15 {1} 16 >>> a - b 17 {1} 18 >>> a.symmetric_difference(b) 19 {1, 4} 20 >>> a ^ b 21 {1, 4} 22 >>> a.copy() 23 {1, 2, 3} 24 >>> a.copy() is a 25 False
堆
模塊heapq中一些重要的函數
函數 描述
heappush(heap, x) 將x壓入堆中
heappop(heap) 從堆中彈出最小的元素
heapify(heap) 讓列表具有堆特徵
heapreplace(heap, x) 彈出最小的元素,並將x壓入堆中
nlargest(n, iter) 返回iter中n個最大的元素
nsmallest(n, iter) 返回iter中n個最小的元素
函數heappush用於在堆中添加一個元素
1 >>> from heapq import * 2 >>> from random import shuffle 3 >>> data = list(range(10)) 4 >>> shuffle(data) 5 >>> heap = [] 6 >>> for n in data: 7 ... heappush(heap, n) 8 ... 9 >>> heap 10 [0, 1, 4, 3, 2, 7, 6, 8, 5, 9] 11 >>> heappush(heap, 0.5) 12 >>> heap 13 [0, 0.5, 4, 3, 1, 7, 6, 8, 5, 9, 2]
函數heappop彈出最小的元素(老是位於索引0處),並確保剩餘元素中最小的那個位於索引0處(保持堆特徵)
1 >>> heappop(heap) 2 0 3 >>> heappop(heap) 4 0.5 5 >>> heappop(heap) 6 1 7 >>> heap 8 [2, 3, 4, 5, 9, 7, 6, 8]
雙端隊列(及其餘集合)
在須要按添加元素的順序進行刪除時,雙端隊列頗有用。在模塊collections中,包含類型deque以及其餘幾個集合collection類型
>>> from collections import deque >>> q = deque(range(5)) >>> q.append(5) >>> q.appendleft(6) >>> q deque([6, 0, 1, 2, 3, 4, 5]) >>> q.pop() 5 >>> q.popleft() 6 >>> q.rotate(3) >>> q deque([2, 3, 4, 0, 1]) >>> q.rotate(-1) >>> q deque([3, 4, 0, 1, 2])
time
模塊time中一些重要的函數
函數 描述
asctime([tuple]) 將時間元組轉換爲字符串
localtime([secs]) 將描述轉換爲表示當地時間的日期元組
mktime(tuple) 將時間元組轉換爲當地時間
sleep(secs) 休眠(什麼都不作)secs秒
strptime(string[,format]) 將字符串轉換爲時間元組
time() 當前時間(重新紀元開始後的秒數,以UTC爲準)
函數time.asctime將當前時間轉換爲字符串
1 >>> import time 2 >>> time.asctime() 3 'Wed Apr 11 20:13:15 2018'
模塊random中一些重要的函數
函數 描述
random() 返回一個0~1(含)的隨機實數
getrandbits(n) 以長整數方式返回n個隨機的二進制位
uniform(a, b) 返回一個a~b(含)的隨機實數
randrange([start], stop, [step]) 從range(start, stop, step)中隨機地選擇一個數
choice(seq) 從序列seq中隨機地選擇一個元素
shuffle(seq[, random]) 就地打亂序列seq
sample(seq, n) 從序列seq中隨機地選擇n個值不一樣的元素
1 from random import * 2 from time import * 3 date1 = (2016, 1, 1, 0, 0, 0, -1, -1, -1) 4 time1 = mktime(date1) 5 date2 = (2017, 1, 1, 0, 0, 0, -1, -1,-1) 6 time2 = mktime(date2) 7 random_time = uniform(time1, time2) #以均勻的方式生成一個位於該範圍內(不包括上限)的隨機數 8 print(asctime(localtime(random_time))) #將這個數轉換爲易於理解的日期
執行結果
1 >>> import shelve 2 >>> s = shelve.open('test.dat') 3 >>> s['x'] = ['a', 'b', 'c'] 4 >>> s['x'].append('d') 5 >>> s['x'] 6 ['a', 'b', 'c']
'd'到哪裏去了呢?
列表['a', 'b', 'c']被存儲到s的'x'鍵下
獲取存儲的表示,並使用它建立一個新列表,再將'd'附加到這個新列表末尾,但這個修改後的版本未被存儲。
最後,再次獲取原來的版本------其中沒有'd'
要正確的修改使用模塊shelve存儲的對象,必須獲取的副本賦給一個臨時變量,並在修改這個副本後再次存儲:
1 >>> temp = s['x'] 2 >>> temp.append('d') 3 >>> s['x'] = temp 4 >>> s['x'] 5 ['a', 'b', 'c', 'd']
一個簡單的數據庫應用程序
1 import sys, shelve 2 3 def store_person(db): 4 pid = input('Enter unique ID number: ') 5 person = {} 6 person['name'] = input('Enter name: ') 7 person['age'] = input('Enter age: ') 8 person['phone'] = input('Enter phone number: ') 9 db[pid] = person 10 11 def lookup_person(db): 12 pid = input('Enter ID number: ') 13 field = input('what would you like to know?(name, age, phone) ') 14 field = field.strip().lower() 15 16 print(field.capitalize() + ':', db[pid][field]) 17 18 def print_help(): 19 print('The available commands are:') 20 print('store : Stores information about a person') 21 print('lookup : Looks up a person from ID number') 22 print('quit : Save changes and exit') 23 print('? : Prints this message') 24 25 def enter_command(): 26 cmd = input('Enter command (? for help): ') 27 cmd = cmd.strip().lower() 28 return cmd 29 30 def main(): 31 database = shelve.open("/opt/python/2.dat") 32 try: 33 while True: 34 cmd = enter_command() 35 if cmd == 'store': 36 store_person(database) 37 elif cmd == 'lookup': 38 lookup_person(database) 39 elif cmd == '?': 40 print_help() 41 elif cmd == 'quit': 42 return 43 finally: 44 database.close() 45 46 if __name__ == '__main__' : main()
模塊re中一些重要的函數
函數 描述
comile(pattern[, flags]) 根據包含正則表達式的字符串建立模式對象
search(pattern, string[, flags]) 在字符串中查找模式
match(pattern, string[, flags]) 在字符串開頭匹配模式
split(pattern, string[, maxsplit=0]) 根據模式來分割字符串
findall(pattern, string) 返回一個列表,其中包含字符串中全部與模式匹配的子串
sub(pat, repl, string[, count=0]) 將字符串中與模式pat匹配的子串都替換爲repl
escape(string) 對字符串中全部的正則表達式特殊字符都進行轉義
函數re.split根據與模式匹配的子串來分割字符串。這相似於字符串方法split,但使用正則表達式來指定分隔符,而不是指定固定的分隔符。使用字符串方法split時,能夠字符串', '爲分割符分割字符串,但使用re. split時,能夠空格和逗號爲分隔符來分割字符串。
1 >>> some_test = 'abcd, aaaa,,,,,bbbb cba' 2 >>> re.split('[, ]+', some_test) 3 ['abcd', 'aaaa', 'bbbb', 'cba']
maxsplit之分最多分割多少次
1 >>> some_test = 'abcd, aaaa,,,,,bbbb cba' 2 >>> re.split('[, ]+', some_test, maxsplit=2) 3 ['abcd', 'aaaa', 'bbbb cba'] 4 >>> re.split('[, ]+', some_test, maxsplit=1) 5 ['abcd', 'aaaa,,,,,bbbb cba']
函數re.findall返回一個列表,其中包含全部與給定模式匹配的子串。
1 >>> pat = '[a-zA-Z]+' 2 >>> text = '"Hm... Err -- are you sure?" he said, sounding insecure.' 3 >>> re.findall(pat, text) 4 ['Hm', 'Err', 'are', 'you', 'sure', 'he', 'said', 'sounding', 'insecure']
查找全部的標點符號
1 >>> text = '"Hm... Err -- are you sure?" he said, sounding insecure.' 2 >>> pat = r'[.?\-",]+' 3 >>> re.findall(pat, text) 4 ['"', '...', '--', '?"', ',', '.']
函數re.sub從左往右將與模式匹配的子串替換爲指定內容
1 >>> pat = '{name}' 2 >>> text = 'Dear {name}...' 3 >>> re.sub(pat, 'Mr. Gumby', text) 4 'Dear Mr. Gumby...'
re.escape是一個工具函數,用於字符串中全部可能被視爲正則表達式運算符的字符進行轉義。
1 >>> re.escape('www.python.org') 2 'www\\.python\\.org' 3 >>> re.escape('But where is the ambiguity?') 4 'But\\ where\\ is\\ the\\ ambiguity\\?'
匹配對象和編組
在模塊re中,查找與模式匹配的子串的函數都在找到時返回MatchObject對象。
在下面的模式中:
'There (was a (wee) (cooper)) who (lived in Fyfe)'
包含以下編組:
0 There was a wee cooper who lived in Fyfe
1 was a wee cooper
2 wee
3 cooper
4 lived in Fyfe
一般,編組包含諸如通配符和重複運算符等特殊字符,所以你可能想知道與給定編組匹配的內容。例如,在下面的模式中:
r'www\.(.+)\.com$'
編組0包含真個字符串,而編組1包含'www.'和'.com'之間的內容。經過建立相似於這樣的模式,可提取字符串中你感興趣的部分。
re匹配對象的重要方法
方法 描述
group([group1, ...]) 獲取與給定子模式(編組)匹配的子串
start([group]) 返回與給定編組匹配的子串的起始位置
end([group]) 返回與給定編組匹配的子串終止位置(與切片同樣,不包含終止位置)
span([group]) 返回與給定編組匹配的子串的起始和終止位置
方法group返回與模式中給定編組匹配的子串。若是沒有指定編組號,則默認爲0.若是隻指定了一個編組號(或使用默認值0),將只返回一個字符串;不然返回一個元組,其中包含與給定編組匹配的子串。
方法start返回與給定編組(默認爲0,即整個模式)匹配的子串的起始索引。
方法end相似於start,但返回終止索引加1.
方法span返回一個元組,其中包含與給定編組(默認爲0,即整個模式)匹配的子串的起始索引和終止索引。
替換中的組號和函數
1 >>> emphasis_pattern = re.compile(r''' 2 ... \* # 起始突出標誌------一個星號 3 ... ( # 與要突出的內容匹配的編組的起始位置 4 ... [^\*]+ # 與除星號外的其餘字符都匹配 5 ... ) # 編組到此結束 6 ... \* # 結束突出的標誌 7 ... ''', re.VERBOSE) 8 >>> re.sub(emphasis_pattern, r'<em>\1</em>', 'Hello, *world*!') 'Hello, <em>world</em>!'