博客搬家自 http://zhouyuanchao.com/wordpress/archives/87
Python具有豐富和強大的庫
** 冪運算符 2**3
pow(2, 3)
abs(-10) 絕對值
round(1.0 / 2.0) 四捨五入到整數
import math 導入math模塊
math.floor(32.9) --> 32
from math import floor
floor(32.9)
變量
x = 3
print("Hello World!")
x = input("prompt:")
轉換爲字符串
str 類型
repr 函數
str(1000L) -> 1000
repr(1000L) -> 1000L
拼接字符串
"Hello " + "World!"
temp = 100
s = "Hello" + str(temp)
raw_input 100 -> '100'
input 100 -> 100
input Hello -> 當做變量
raw_input Hello -> 'Hello' 字符串
print ("Hello, \
World") -> "Hello, World"
長字符串
""" string """ 保留換行,和特殊字符比如' "
''' string '''
原始字符串 不會轉義,最後一個字符不能是\
r'Hello,\nWorld!' -> 'Hello,\nWorld'
Unicode字符串
u'Hello World'
基本類型
str int long
序列
a1 = ['Hello', 100]
str = 'Hello'
str[0] -> 'H'
str[-1] -> 'o'
分片 第一二個參數分別是元素索引[index1, index2)
a1 = [1, 2, 3, 4, 5]
a1[0:3] -> [1,2,3]
a1[0:] -> 0到結尾
a1[:] -> 所有元素
a2[0:3:1] ->第三個參數步長,默認爲1
序列連接
[1,2,3] + [4,5,6]
'Hello ' + 'World'
[1,2,3] + 'Hello' # Error,相同類型的序列才能相加
序列乘以數字n : 序列重複n次
'python' * 4
pythonpythonpythonpython
空序列
[]
[None] * 10 None表示什麼都沒有 類似c++中的NULL
判斷是否在序列中
permissions = 'rw'
'w' in permissions -> True
內建函數 len min max
len 返回序列中元素個數
min(2,4,6)
列表、元組屬於序列
列表 可變序列
元組 不可變序列
元素賦值
x = [1, 1, 1]
x[1] = 2 -> [1, 2, 1]
刪除元素
names = ['Alice', 'Beth', 'Cecil']
del names[2]
分片賦值
names[1:] = ['a', 'b']
list('Hello') 轉換爲可變序列
names.append('Hello')
names.count('Alice') 元素出現的次數
list tuple str 類型
a.extend(b) 拼接,修改a
a.index('who') 查找元素 返回索引,找不到將引發異常
a.insert(index, value)
a.pop(index) 移除,如果不指定index,刪除最後一個
a.remove(value)
a.reverse()
a.sort()
sorted(a) 返回排序副本
內建比較函數 cmp()
cmp(100, 200) -> -1
元組
不能修改
1,2,3 -> (1,2,3)
(1,2,3) -> (1,2,3)
() 空元組
(42,) 包含一個值的元組
tuple 類型非函數 以一個序列作爲參數並把它轉換爲元組
tuple([1,2,3]) -> (1,2,3)
tuple('abc') -> ('a','b','c')
tuple((1,2,3)) -> (1,2,3)
字符串方法
find 沒有找到返回-1
"With a moo-moo here, and a moo-moo there.".find('moo')
title = "Monty python"
title.find('Monty')
table = maketrans('ABC', 'abc')
word = 'ABC'
word.translate(table)
字典
phonebook = {'Alice':'2341', 'Beth':'9120}
空字典 {}
dict 類型 通過對其他映射或者(鍵值)這樣的序列對建立字典
items = [('name','Gumby'), ('age',42)]
d = dict(items)
d = dict(name='Gumby', age=42)
基本字典操作
len(d)
d[k]
d[k] = v
del d[k]
k in d
import module
-- module.function()
from module import function
-- function()
import math as foobar
-- foobar.sqrt(100)
from math import sqrt as foobar
同一行輸出
print 'Hello',
print 'world!'
if xxx:
print 'Hello'
elif xxx:
print ...
else:
print 'Hi'
比較運算符可以連接
0<age<100
== 值相等 可以比較序列的值
is 引用相等 (避免用於比較類似數值和字符串這類不可變值)
邏輯運算符
and or not
三元運算符 c中的 ? :
a = b and c or d
c if b else d
# while循環
x=1
while x<=100:
print x
x+=1
# for 循環
words=['this','is','an','ex','parrot']
for word in words:
print word
range(0, 10) 結果是一個序列
zip 函數
names = ['anne', 'beth', 'george', 'damon']
ages = [12, 45, 32, 102]
zip(names, ages)
[('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)]
for index, string in enumerate(strings):
if 'xxx' in string:
strings[index] = '[censored]'
函數 reversed sorted
循環的else子句 沒有調用break時執行
for n in range(99, 81, -1)
root = sqrt(n)
if root == int(root):
print n
break
else:
print "Didn't find it!"
列表推導式
[x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
#註釋
字典 引用
a = None
什麼都不做的語句 pass
刪除名稱
x = ["Hello", "World]
del x
執行字符串中的Python代碼
exec "print 'Hello, world!'"
exec("print 'Hello, world!'") #Python3.0
命名空間
from math import sqrt
scope = {}
exec 'sqrt = 1' in scope
sqrt(4) # ->2.0
scope['sqrt'] # ->1
eval 計算表達式值
函數是否可調用
callable(x)
Python3.0 hasattr(func, __call__)
定義函數
def hello(name):
return 'Hello. ' + name + '!'
#註釋
文檔字符串 def語句後面、模塊或者類的開頭
def square(x):
'Calculates the square of the number x.'
return x * x
square.__doc__ # 輸出 'Calculates ... '
help函數
help(square)
非位置參數(與位置無關)
調用函數時,指明參數名
def func(greeting, name):
print '%s, %s' % (greeting, name)
func(greeting='Hello', name='world')
參數默認值
def func(greeting='Hello', name='world'):
pass
*收集參數到元組
def func(*params):
print params
func(1, 2, 3) # 輸出(1, 2, 3)
**收集關鍵字參數到字典
在調用函數時使用 * ** 將元組或字典解包成參數
vars() 返回當前作用域字典
globals() 返回全局作用域字典
locals()
給全局變量賦值
x = 1
def func():
global x
x = x + 1
閉包概念 類似lua
lambda表達式
lambda 數學中表示匿名函數
一切用遞歸實現的功能都可以用循環實現,但有時遞歸更易讀。
遞歸的一個侷限,有耗盡棧空間的風險。
map(func, seq) 對序列中的每個元素應用函數
filter(func, seq) 返回其函數爲真的元素的列表
isinstance(object, tuple)
isinstance(object, dict)
#爲變量隨機賦值
from random import choice
x = choice(['Hello, world!', [1,2,'e','e',4]])
repr函數 輸出變量文本表示
x = 'Fnord'
print repr(x)
type
isinstance
issubclass
創建類
__metaclass__ = type # 確定使用新式類,需要在模塊或腳本開始的地方放置,python3不需要
class Person:
def setName(self, name):
self.name = name
def getName(self):
return self.name
def greet(self):
print "Hello, world! i'm %s." % self.name
類中的變量和self.變量不是同一個,前者所有實例共享,後者是實例的私有變量。
foo = Person() #創建實例
foo.setName('Hello')
foo.greet()
Person.setName(foo, 'Hello')
私有實現方式
前面加__
但仍然可以訪問
s._類名__函數名()
指定超類
class Filter:
...
class SPAMFilter(Filter):
...
issubclass(SPAMFilter, Filter) ->True
獲取基類
SPAMFilter.__bases__
一個對象屬於哪個類
s.__class__
type(s) # 使用__metaclass__=type 或從object繼承
tc是否包含talk特性
hasattr(tc, 'talk')
是否可調用
callable(getattr(tc, 'talk', None))
Python3.0 hasattr(x, '__call__')
術語
特性 成員變量
方法 成員函數
異常處理
異常類 從Exception繼承
引發異常 raise Exception # 會自動創建實例
raise Exception('hyperdrive overload')
內建異常 exceptions模塊
dir函數 列出模塊的內容
import exceptions
dir(exceptions)
最重要的內建異常類:146頁
捕獲異常
try:
x = 12
y = 0
print x / y
except ZeroDivisionError:
print "The second number can't be zero!"
except TypeError:
print "That wasn't a number, was it?"
// 多個異常作爲元組列出
except (ZeroDivisionError, TypeError, NameError):
print 'Your number were bogus...'
重新拋出捕獲的異常
raise # 無參數
獲得異常實例
except (ZeroDivisionError, TypeError), e:
print e
Python3.0
except (ZeroDivisionError, TypeError) as e:
捕獲所有異常
except:
print 'Something wrong happened...'
else:
pass # 沒有異常發生時纔會執行
finally:
pass # 不管是否發生異常,都會執行
__future__
兩邊帶下劃線的被稱爲魔法或特殊方法
實現這些方法,這些方法會在特殊情況下被Python調用
構造函數
def __init__(self):
self.somevar = 42
析構函數
__del__
因爲有垃圾回收機制,所以避免使用__del__
調用父類的構造函數
方法1
class SongBird(Bird):
def __init__(self):
Bird.__init__(self)
self.sound = 'Squawk!'
方法2
class SongBird(Bird):
def __init__(self):
super(SongBird, self).__init__()
self.sound = 'Squawk!'
靜態方法 類成員方法
def smeth():
pass
smeth = staticmethod(smeth)
def cmeth():
pass
cmeth = classmethod(cmeth)
@staticmethod
def smeth():
pass
@classmethod
def cmeth(cls):
pass
MyClass.smeth()
MyClass.cmeth()
一個實現了__iter__方法的對象是可迭代的,一個實現了next方法的對象則是迭代器。
內建函數iter可以從可迭代的對象中獲得迭代器
it = iter([1,2,3])
it.next() ->1
it.next() ->2
將迭代器或迭代對象轉換爲序列
ti = TestIterator()
list(ti) -> [...]
任何包含yield語句的函數稱爲生成器
nested = [[1, 2], [3, 4], [5]]
def flatten(nested):
for sublist in nested:
for element in sublist:
yield element
for num in flatten(nested):
print num
生成器是逐漸產生結果的複雜遞歸算法的理想實現工具。
--第10章--
充電時刻
import sys
sys.path.append('c:/python')
告訴解釋器除了從默認的目錄中尋找之外,還需要從目錄c:/python中尋找模塊
.py .pyw (windows系統)
.pyc 平臺無關的 經過處理(編譯)的,已經轉換成Python能夠更加有效地處理的文件。
導入模塊的時候,其中的代碼被執行。重複導入,不會重複執行。
強制重新導入 reload(hello) # hello - 模塊名 Python3.0已經去掉
.py 文件 導入後文件名就是模塊名作用域
主程序 __name__ -> '__main__'
import __name__ -> '__模塊名__'
模塊中的測試代碼可以使用__name__判斷是否執行測試代碼。
pprint模塊中pprint函數 提供更加智能的打印輸出,比如列表分行輸出。
sys.path
PYTHONPATH 環境變量
包 - 目錄
目錄中包含__init__.py文件
查看模塊包含的內容可以使用dir函數,他會將對象(以及模塊的所有函數、類、變量等)的所有特性列出
dir(sys) -> 列表['a', 'b', ...]
from copy import *
copy.__all__ 過濾
如果沒有設定__all__ 用import *語句默認導出所有不以下劃線開頭的全局名稱。
help(copy.copy) copy模塊中的copy函數
print copy.copy.__doc__
模塊的源代碼
print copy.__file__
標準庫
-sys
argv
exit([arg])
modules
path
platform
stdin
stdout
stderr
-os
environ
system(command)
sep
pathsep
linesep
urandom(n)
webbrowser模塊
-fileinput
input
filename()
lineno()
filelineno()
isfirstline()
isstdin()
nextfile()
close()
-collections
-heapq #堆
-time
-random
-shelve #序列化 保存到文件
-re #正則表達式
open 默認讀模式
+ 參數可以用到其他任何模式中,指明讀和寫都是允許的。比如r+能在打開一個文件用來讀寫時使用。
r 讀模式
w 寫模式
a 追加模式
b 二進制模式 (可添加到其他模式中使用)
rb 讀取二進制文件
f = open(r'c:\file.txt', 'w')
f.write('0112345')
f.seek(5)
f.close()
f.read()
file.readline() 讀取一行 (包含換行符)
file.readlines()
# Open your file here
try:
# Write data to your file
finally:
file.close()
# Python2.5 from __future__ import with_statement
# 自動close
with open("somefile.txt") as somefile:
with 上下文管理 __enter__ __exit__ contextlib模塊
do_something(somefile)
當到達文件末尾時,read方法返回一個空的字符串。
import fileinput
for line in fileinput.input(filename):
pass
數據庫
Python DB API的模塊特性
apilevel 所使用的Python DB API版本
threadsafety 模塊的線程安全等級
paramstyle 在SQL查詢中使用的參數風格
import sqlite3
conn = sqlite3.connect('somedatabase.db')
curs = conn.cursor()
conn.commit()
conn.close()
socket模塊
# 服務器
import socket
s = socket.socket()
host = socket.gethostname()
port = 1234
s.bind((host, port))
s.listen(5)
while True:
c.addr = s.accept()
print 'Got connection from' , addr
c.send('Thank you for connecting')
c.close()
# 客戶端
import socket
s = socket.socket()
host = socket.gethostname()
port = 1234
s.connect((host, port))
print s.recv(1024)
urllib urllib2模塊
能讓通過網絡訪問文件,就像那些文件存在於你的電腦上一樣。通過一個簡單的函數調用,幾乎可以把任何URL所指向的東西用作程序的輸入。
如果需要使用HTTP驗證或cookie或者要爲自己的協議寫擴展程序的話,urllib2是個好的選擇。
標準庫中一些與網絡相關的模塊
服務器框架
SocketServer
BaseHTTPServer
SimpleHTTPServer
CGIHTTPServer
SimpleXMLRPCServer
DocXMLRPCServer
基於SocketServer的服務器
from SocketServer import TCPServer, StreamRequestHandler
class Handler(StreamRequestHandler):
def handle(self):
addr = self.request.getpeername()
print 'Got connection from', addr
self.wfile.write('Thank you for connection')
server = TCPServer(('', 1234), Handler)
server.serve_forever()
Twisted 一個非常強大的異步網絡編程框架
import fileinput
for line in fileinput.input(filename):
process(line)
inplace=1 # 標準輸出會被重定向到打開文件
import fileinput
for line in fileinput.input(inplace = 1):
line = line.rstrip()
num = fileinput.lineno()
print '%-40s # %2i' % (line, num)
文件是一個可迭代對象
f = open(filename)
for line in f:
process(line)
f.close()
使用默認瀏覽器打開某個網址
import webbrowser
webbrowser.open('www.baidu.com')
集合 set
set([0, 1, 2, 3])
set會剔除重複元素
set的元素順序是隨意的
a = set([1, 2, 3])
b = set([2, 3, 4])
並集 a.union(b) a | b
交集 a.intersection(b) b & b
a.issuperset(b)
a.issubset()
a.difference(b) a - b
a.symmetric_difference(b) a ^ b
a.copy()
reduce(func, [a, b, c])
reduce執行以下步驟
tmp = func(a, b)
tmp = func(tmp, c)
...
time 模塊
time() 當前時間 - 1970至今的秒數
localtime() 將秒數轉換爲日期元組,本地時間
asctime() 將日期元組轉換爲字符串
mktime() 將日期元組轉換爲本地時間(秒數) 與localtime()功能相反
sleep()
datetime 模塊
支持日期和時間的算法
timeit 模塊
幫助開發人員對代碼段的執行時間進行計時
random 模塊
random() 0<= n < 1
randrange([start], stop, [step]) [start, stop) 隨機整數
uniform(a, b) [a, b] 隨機實數
choice() 從給定序列中選擇隨機元素
shuffle() 將給定(可變)序列的元素進行隨機移位
sample() 從給定序列中 選擇給定數目的元素,同時確保元素互不相同
re 正則表達式模塊
compile(pattern, [flags]) 根據包含正則表達式的字符串創建模式對象
search(pattern, string, [flags]) 在字符串中尋找模式,返回第一個匹配的MatchObject
match(pattern, string, [flags]) 在字符串的開始處匹配模式,返回MatchObject
split(pattern, string, [maxsplit=0]) 根據模式的匹配項來分割字符串,返回列表
findall(pattern, string) 列出字符串中模式的所有匹配項,返回列表
sub(pat, repl, string, [count=0])將字符串中所有pat匹配項用repl替換
escape(string) 將字符串中所有特殊正則表達式字符轉義
pattern =
re.sub(pattern, r'<em>\1</em>', 'Hello, *world*!')
\1 引用模式匹配中的組
模式匹配默認是貪婪模式
所有的重複運算符都可以通過在其後面加上一個問號變成非貪婪版本
string模塊中的模板系統 template類
functools 通過部分參數來使用某個函數,稍後再爲剩下的參數提供數值
difflib 這個庫讓你可以計算兩個序列的相似程度,
還能讓你在一些序列中找出和提供的原始序列最像的那個。
可以用於創建簡單的搜索程序
hashlib 如果爲兩個不同的字符串計算出了簽名。幾乎可以確保這兩個簽名完全不同。
加密和安全性 見 md5 sha 模塊
csv 讀寫csv文件
timeit profile trace
itertools
logging
getopt optparse
cmd
項目3 萬能的XML
from xml.sax.handler import ContentHandler
from xml.sax import parse
class MyHandler(ContentHandler):
parse('website.xml', MyHandler)
str.capitalize()
getattr()
callable()
os.makedirs('foo/bar/baz')
os.path.isdir()
a = ['hello']
*a + ['boys'] -> * (a + ['boys'])
項目4 新聞聚合
nntplib
NNTP(Network News Transfer Protocal,網絡新聞組傳輸協議)
urllib
strftime('%y%m%d') # 年月日
strftime('%H%M%S') # 時分秒
servername = 'news.foo.bar' # 服務器地址
group = 'comp.lang.python.announce'
server = NNTP(servername)
ids = server.newnews(group, date, hour)[1] # 文章的ID號
head = server.head(id)[3]
for line in head:
if line.lower().startswith('subject:'):
subject = line[9:]
break
body = server.body(id)[3] # 返回一個字符串列表
打印完所有文章後 調用server.quit()
list.extend(list)
list.append(object)
BBC新聞網頁的HTML頁面佈局可能會變,如果這樣的話就需要重寫正則表達式。
在使用其他頁面的時候也要注意這樣的情況。要查看HTML源代碼然後試着去找到適用的匹配模式。
file
str
unicode
zlib
gzip
bz2
zipfile
tarfile
shutil