第四章 python
模塊正則表達式
引用外部模塊數據庫
Import mathwindows
Math.sin(0)api
自定義模塊的導入app
#hello.py 文件的保存位置是D:\workspace_pythondom
Print(‘hello world!’)函數
#添加到環境變量中oop
Import 測試
Sys.path.append(‘D:\workspace_python’)
>>>import hello
Hello world!
若是再次調用,就不會輸出打印語句
在模塊中定義函數
#hello2.py
Def hello():
Print(‘hello world’)
>>>Import hello2
>>>Hello2.hello()
Hello world!
在模塊中添加測試代碼
#hello4.py
Def hello():
Print(‘hello world’)
Def test():
Hello()
#只有它做爲主程序運行時,測試方法纔會被執行
If __name__==’__main__’:test()
讓模塊可用;
1 將模塊放到正確的位置
#輸出環境變量
>>> import sys,pprint
>>> pprint.pprint(sys.path)
['',
'D:\\Python32\\Lib\\idlelib',
'D:\\Python32',
'C:\\windows\\system32\\python32.zip',
'D:\\Python32\\DLLs',
'D:\\Python32\\lib',
#最佳路徑
'D:\\Python32\\lib\\site-packages',
'D:\\Python32\\lib\\site-packages\\wx-3.0-msw']
2 告訴解釋器到哪裏去找
在PYTHONPATH中添加模塊所在的目錄
3 模塊的命名
是以.py爲擴展名,在windows中也能夠使用pyw爲擴展名
包
包名/模塊名.py
探究模塊
#查看模塊中包含的內容:
>>>import copy
[n for n in dir(copy) if not n.startswith('_')]
['Error', 'PyStringMap', 'builtins', 'copy', 'deepcopy', 'dispatch_table', 'error', 'name', 't', 'weakref']
#查看模塊的公有接口:
>>> copy.__all__
['Error', 'copy', 'deepcopy']
#使用help來取得幫助信息
>>> help(copy.copy)
Help on function copy in module copy:
copy(x)
Shallow copy operation on arbitrary Python objects.
See the module's __doc__ string for more info.
#查看函數的文檔信息
>>> print(range.__doc__)
range([start,] stop[, step]) -> range object
Returns a virtual sequence of numbers from start to stop by step.
#查看函數源碼的存放位置
>>> print(copy.__file__)
D:\Python32\lib\copy.py
標準庫
1 sys 訪問與python解釋器有聯繫的變量和函數
Argv
Exit([argv])
Modules
Path
Platform
Stdin
Stdout
Stderr
2 os 訪問多個操做系統的功能
Environ
System(command)
Sep
Pathsep
Linesep
Urandom(n)
3 fileinput 遍歷文本文件中的全部行
Input
Filename()
Lineno()
Filelineno()
Isfirstline()
Isstdin()
Nextfile()
Close()
集合 堆和雙端隊列
1 集合 set
>>> set(range(10))
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
#無重複,檢查成員資格
>>> set([0,1,2,3,4,5,0,1,2,3,4,5])
{0, 1, 2, 3, 4, 5}
#求並集和交集,對整數進行位操做
>>> a=set([1,2,3])
>>> b=set([2,3,4])
>>> a.union(b)
{1, 2, 3, 4}
>>> a|b
{1, 2, 3, 4}
Set 的經常使用方法
Add
Remove
Issubset
Issuperset
Intersection
Difference
Symmetric_dirrerence()
copy
#集合是可變的不能用做字典的鍵
2 堆 heap
#經常使用的幾個函數
Heappush #x入堆
Heappop #最小元素彈出
Heapify #
Heapreplace(heap,x) #將最小的元素彈出,將x放入
Mlargest(n,iter) #第n個大小元素
Nsmallest(n,iter) #第n個小的元素
3 雙端隊列 deque
#在須要按照元素增長的順序來移除元素時很是重要
>>> 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
取得當前時間,
操做時間和日期
從字符串讀取時間
格式化時間字符串
#經常使用函數
Asctime #時間元組轉字符串
Localtime #秒數轉爲時間元組
Mktime # 時間元組轉爲本地時間
Sleep #休眠
Strptime #字符串解析爲時間元組
Time #當前時間
Random 返加隨機數
#經常使用函數
Rondom #返加隨查數
Getrandbits(n) #返回長整型隨機數
Uiform(a,b) #返回隨機實數
Randrange([start],stop,[step]) #
Choice(sep) #從序列中返回隨機數
Shuffle(seq[,random]) #原地指定序列
Sample(seq,n) # 從序列中返回n個獨立的隨機數
Shelve 簡單的存儲方案
#簡單的數據庫應用程序
#database.py
import sys, shelve
def store_person(db):
'''
query user for data and store it in the shelf object
'''
pid=input('Enter unique ID number: ')
person={}
person['name']=input('Enter name: ')
person['age']=input('Enter age: ')
person['phone']=input('Enter phone number: ')
db[pid]=person
def lookup_person(db):
'''
query user for ID and desired field. and fetch the corresponding data form
the shelf object
'''
pid=input('Enter ID number: ')
field=input('what would you like to know?(name,age,phone)')
field=field.strip().lower()
print(field.capitalize()+':',db[pid][field])
def print_help():
print('The available commands are: ')
print('store : stores information about a persion')
print('lookup : looks up a persion from ID number')
print('quit : save changes and exit')
print('? : prints this message')
def enter_command():
cmd=input('Enter command (? for help): ')
cmd=cmd.strip().lower()
return cmd
def main():
#打開數據文件
database=shelve.open('c:\\database.dat')
try:
while True:
cmd=enter_command()
if cmd=='store':
store_person(database)
elif cmd=='lookup':
lookup_person(database)
elif cmd=='?':
print_help()
elif cmd=='quit':
return
finally:
database.close()
if __name__=='__main__':main()
測試結果以下:>>>
Enter command (? for help): ?
The available commands are:
store : stores information about a persion
lookup : looks up a persion from ID number
quit : save changes and exit
? : prints this message
Enter command (? for help): store
Enter unique ID number: 001
Enter name: retacn
Enter age: 32
Enter phone number: 18816179937
Enter command (? for help): lookup
Enter ID number: 001
what would you like to know?(name,age,phone)name
Name: retacn
Enter command (? for help): lookup
Enter ID number: 001
what would you like to know?(name,age,phone)phone
Phone: 18816179937
Enter command (? for help): quit
Re 對正則表達式的支持
通配符 (.)單個字符
對特殊字符進行轉議(\\)
字符集
範圍[a-z]
[a-zA-Z0-9]
[^abc]除了abc外的任意字符
選擇符和子模式
管道符號(|) python|perl
子模式() p(ython|erl)
可選項和重複子模式
可選項()? 子模式後加門號
R’htt://)?(www\.)?python\.org’
重複子模式
(pattern)* #重複0次或屢次
(pattern)+ #重複一次或屢次
(patern){m,n} #重複m-n次
字符串的開始和結尾
^開始
$結束
Re模塊的內容
經常使用函數:
Compile(pattern[,flags]) #根據正則表達式的字符串建立模式對象
Search(parth,string[,flags]) #在字符串中尋找模式
Match(pattern,string[,flags]) #在字符串開始處匹配對象
Split(pattern,string[,maxsplit=0]) #根據模式的配匹配項來分割字符串
Findall(pattern,string) #列出字符串中模式的全部匹配項
Sub(pat,repl,string[,count=0]) #將字符串中全部pat的匹配項用repl替換
Escap(string) #將字符串中全部特殊正則表達式字符轉義
配匹對象和組
組就是放置在圓括號內的子模式
示例代碼以下:
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
Re中匹配對象的重要方法
Group([group1],...) #給定子模式的匹配項
Start([group]) # 匹配項的開始伴位置
End([group]) #匹配項的結束位置
Span([group]) #返回一個組的開始和結束位置
找出email的發信人
一個簡單的模板
# templates.py
import fileinput, re
# Matches fields enclosed in square brackets:
field_pat = re.compile(r'\[(.+?)\]')
# We'll collect variables in this:
scope = {}
# This is used in re.sub:
def replacement(match):
code = match.group(1)
try:
# If the field can be evaluated, return it:
return str(eval(code, scope))
except SyntaxError:
# Otherwise, execute the assignment in the same scope...
exec code in scope
# ...and return an empty string:
return ''
# Get all the text as a single string:
# (There are other ways of doing this; see Chapter 11)
lines = []
for line in fileinput.input():
lines.append(line)
text = ''.join(lines)
# Substitute all the occurrences of the field pattern:
print field_pat.sub(replacement, text)