<python基礎教程(第二版)>html
http://www.cnblogs.com/fnng/category/454439.htmlpython
eg:web
>>> numbers = [0,1,2,3,4,5,6,7,8,9]正則表達式
>>> numbers[7:-1] shell
===================================小程序
[] --> 列表數組
()--> 元組多線程
===================================app
dict函數框架
能夠用dict 函數,經過其餘映射(好比其餘字典)或(鍵,值)這樣的序列對創建字典。
eg:
>>> items = [('name','gumby'),('age',42)] >>> d = dict(items) >>> d {'age': 42, 'name': 'gumby'} >>> d['name'] 'gumby'
===================================
>>> scoundrel ={'name':'robin','girlfriend':'marion'} >>> key,value = scoundrel.popitem() >>> key 'name' >>> value 'robin'
>>> x += 1 #(x=x+1) >>> x *= 2 #(x=x*2)
d = {'x':1,'y':2,'z':3} for key in d: print key,'corresponds to',d[key] #輸出 >>> y corresponds to 2 x corresponds to 1 z corresponds to 3
from math import sqrt for n in range(99,0,-1): root = sqrt(n) if root == int(root): print n break #輸出 >>> 81
==========================================================================================
默認參數 對於一些參數,咱們但願它的一些參數是可選的,若是用戶不想要爲這些參數提供值的話,這些參數就使用默認值。
def say(message,times=1): print message*times say('Hello') say('World',5) #輸出 >>> Hello WorldWorldWorldWorldWorld
def func(a,b=5,c=10): print 'a is',a, 'and b is',b,'and c is',c func(3,7) func(24,c=32) func(c=23,a=14)
=======================================================
>>> def add(x,y): return x+y >>> add(1,2) 3 >>> add('hello.','world') 'hello.world'
>>> def length_message(x):
print"The length of " , repr(x),"is",len(x)
>>> length_message('chongshi') The length of 'chongshi' is 8
==================================================================
try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except ZeroDivisionError: print "輸入的數字不能爲0!"
class MuffledCalulator: muffled = False #這裏默認關閉屏蔽 def calc(self,expr): try: return eval(expr) except ZeroDivisionError: if self.muffled: print 'Divsion by zero is illagal' else: raise #運行程序: >>> calculator = MuffledCalulator() >>> calculator.calc('10/2') 5 >>> calculator.clac('10/0') Traceback (most recent call last): File "<pyshell#30>", line 1, in <module> calculator.clac('10/0') AttributeError: MuffledCalulator instance has no attribute 'clac' #異常信息被輸出了 >>> calculator.muffled = True #如今打開屏蔽 >>> calculator.calc('10/0') Divsion by zero is illagal
try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except ZeroDivisionError: print "輸入的數字不能爲0!" except TypeError: # 對字符的異常處理 print "請輸入數字!"
try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except (ZeroDivisionError,TypeError,NameError): print "你的數字不對!"
try: x = input('Enter the first number: ') y = input('Enter the second number: ') print x/y except: print '有錯誤發生了!'
====================================
構造方法
構造方法與其的方法不同,當一個對象被建立會當即調用構造方法。建立一個python的構造方法很簡答,只要把init方法,從簡單的init方法,轉換成魔法版本的_init_方法就能夠了。
class FooBar: def __init__(self): self.somevar = 42 >>> f =FooBar() >>> f.somevar 42
調用未綁定的超類構造方法
使用super函數
super函數只能在新式類中使用。當前類和對象能夠做爲super函數的參數使用,調用函數返回的對象的任何方法都是調用超類的方法,而不是當前類的方法。那就能夠不一樣在SongBird的構造方法中使用Bird,而直接使用super(SongBird,self)。
... super(SongBird,self).__init__() ...
def __init__(self): self.width = 0 self.height = 0
=========================================================
迭代器(無限循環)
迭代的意思是重複作一些事不少次---就像在循環中作的那樣。__iter__ 方法返回一個迭代器,所謂迭代器就是具備next方法的對象,在調用next方法時,迭代器會返回它的下一個值。若是next方法被調用,但迭代器沒有值能夠返回,就會引起一個StopIteration異常。
class Fibs: def __init__(self): self.a = 0 self.b = 1 def next(self): self.a , self.b = self.b , self.a + self.b return self.a def __iter__(self): return self >>> fibs = Fibs() >>> for f in fibs: if f > 1000: print f break #由於設置了break ,因此循環在這裏中止。 1597
class TestIterator: value = 0 def next(self): self.value += 1 if self.value > 10: raise StopIteration return self.value def __iter__(self): return self >>> ti = TestIterator() >>> list(ti) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
生成器也叫 簡單生成器,生成器能夠幫助讀者寫出很是優雅的代碼,固然,編寫任何程序時不使用生成器也是能夠的。
>>> def flatten(nested): for sublist in nested: for element in sublist: yield element >>> nested = [[1,2],[3,4],[5]] #使用for循環 >>> for num in flatten(nested): print num 1 2 3 4 5
生成器新屬性是在開始運行後爲生成器提供值的能力。表現爲生成器和「外部世界」進行交流的渠道:
* 外部做用域訪問生成器的send方法,就像訪問next 方法同樣,只不過前者使用一個參數(發送的「消息」---任意對象)
* 在內部則掛起生成器,yield如今做爲表達式而不是語句使用,換句話說,當生成器從新運行的時候,yield方法返回一個值,也就是外部經過send方法發送的值。若是next 方法被使用,那麼yield方法返回None.
下面簡單的方例子來講明這種機制:
def repeater(value): while True: new =(yield value) if new is not None:value = new >>> r = repeater(42) >>> r.next() 42 >>> r.send("hello, world!") 'hello, world!'
生成器的另兩個方法:
* throw方法(使用異常類型調用,還有可選的值以及回溯對象)用於在生成器內引起一個異常(在yield表達式中)
* close 方法(調用時不用參數)用於中止生成器。
>>> import sys >>> sys.path.append('c:/python') >>> import hello hello,world!
python文件的後綴爲.py ,.py文件能夠用來直接運行,就像一個獨立的小程序;也能夠用來做爲模塊被其它程序調用。
__name__是模塊的內置屬性,若是等於'__main__' 側表示直接被使用,那麼將執行方法test()方法;若是是被調用則不執行 if 判斷後面的test()方法。
time.asctime()
'Thu May 16 00:00:08 2013'
random模塊包括返回隨機的函數,能夠用於模擬或者用於任何產生隨機輸出的程序。
random模塊中的一些重要函數:
** 通配符
正則表達式能夠匹配多於一個的字符串,你可使用一些特殊字符建立這類模式。好比點號(.)能夠匹配任何字符。在咱們用window 搜索時用問號(?)匹配任意一位字符,做用是同樣的。那麼這類符號就叫 通配符。
** 對特殊字符進行轉義
使用「python\\.org」,這樣就只會匹配「python.org」了
** 字符集
咱們可使用中括號([ ])括住字符串來建立字符集。可使用範圍,好比‘[a-z]’可以匹配a到z的任意一個字符,還能夠經過一個接一個的方式將範圍聯合起來使用,好比‘[a-zA-Z0-9]’可以匹配任意大小寫字母和數字。
反轉字符集,能夠在開頭使用^字符,好比‘[^abc]’能夠匹配任何除了a、b、c以外的字符。
** 選擇符
有時候只想匹配字符串’python’ 和 ’perl’ ,可使用選擇項的特殊字符:管道符號(|) 。所以, 所需模式能夠寫成’python|perl’ 。
** 子模式(加括號)
可是,有些時候不須要對整個模式使用選擇符---只是模式的一部分。這時可使用圓括號起須要的部分,或稱子模式。 前例能夠寫成 ‘p(ython | erl)’
** 可選項
在子模式後面加上問號,它就變成了可選項。它可能出如今匹配字符串,但並不是必須的。
** 重複子模式
(pattern)* : 容許模式重複0次或屢次
(pattern)+ : 容許模式重複1次或屢次
(pattern){m,n} : 容許模式重複m~ n 次
re模塊中一些重要的函數:
re.split 會根據模式的匹配項來分割字符串。
re. findall以列表形式返回給定模式的全部匹配項。
re.sub的做用在於:使用給定的替換內容將匹配模式的子符串(最左端而且重疊子字符串)替換掉。
re.escape 函數,能夠對字符串中全部可能被解釋爲正則運算符的字符進行轉義的應用函數。若是字符串很長且包含不少特殊字符,而你又不想輸入一大堆反斜線,可使用這個函數。
簡單來講,組就是放置在圓括號裏內的子模塊,組的序號取決於它左側的括號數。
re 匹配對象的重要方法
=========================================================
open函數中模式參數的經常使用值
readline返回一行的字符串, readlines返回包含文件全部內容的字符串列表, 每一個元素是一行的字符串。
pprint 模塊的pprint方法將內容分紅每一個小項單行顯示。
>>> f = open(r'I:\python\test.txt') >>> lines = f.readlines() >>> lines[1] = "isn't a\n" >>> f = open(r'I:\python\test.txt','w') >>> f.writelines(lines) >>> f.close()
>>> first,second,third = open(r'I:\python\test.txt') >>> first 'First line\n' >>> second 'Second line\n' >>> third 'Third line\n'
===========================================================================================================
圖形用戶界面
import wx # 須要導入wx模塊 app = wx.App() win = wx.Frame(None) win.Show() app.MainLoop()
假設寫了一個負責打開文件的函數,並將其命令爲load ,而後就能夠像下面這樣將函數做爲loadButton的事件處理函數:
loadButton.Bind(wx.EVT_BUTTON,load)
================================================================
什麼是進程?
計算機程序只不過是磁盤中可執行的,二進制(或其它類型)的數據。它們只有在被讀取到內存中,被操做系統調用的時候纔開始它們的生命期。進程(有時被稱爲重量級進程)是程序的一次執行。每一個進程都有本身的地址空間,內存,數據棧以及其它記錄其運行軌跡的輔助數據。操做系統管理在其上運行的全部進程,併爲這些進程公平地分配時間。
什麼是線程?
線程(有時被稱爲輕量級進程)跟進程有些類似,不一樣的是,全部的線程運行在同一個進程中,共享相同的運行環境。咱們能夠想像成是在主進程或「主線程」中並行運行的「迷你進程」。
thread.allocate_lock()
返回一個新的鎖定對象。
acquire() /release()
一個原始的鎖有兩種狀態,鎖定與解鎖,分別對應acquire()和release() 方法。
thread.start_new_thread(loop0, ())
#coding=utf-8 import thread from time import sleep, ctime loops = [4,2] def loop(nloop, nsec, lock): print 'start loop', nloop, 'at:', ctime() sleep(nsec) print 'loop', nloop, 'done at:', ctime() #解鎖 lock.release() def main(): print 'starting at:', ctime() locks =[] #以loops數組建立列表,並賦值給nloops nloops = range(len(loops)) for i in nloops: lock = thread.allocate_lock() #鎖定 lock.acquire() #追加到locks[]數組中 locks.append(lock) #執行多線程 for i in nloops: thread.start_new_thread(loop,(i,loops[i],locks[i])) for i in nloops: while locks[i].locked(): pass print 'all end:', ctime() if __name__ == '__main__': main()
__init__()
方法在類的一個對象被創建時運行。這個方法能夠用來對你的對象作一些初始化。
apply()
apply(func [, args [, kwargs ]]) 函數用於當函數參數已經存在於一個元組或字典中時,間接地調用函數。args是一個包含將要提供給函數的按位置傳遞的參數的元組。若是省略了args,任何參數都不會被傳遞,kwargs是一個包含關鍵字參數的字典。
apply() 用法:
#不帶參數的方法 >>> def say(): print 'say in' >>> apply(say) say in #函數只帶元組的參數 >>> def say(a,b): print a,b >>> apply(say,('hello','蟲師')) hello 蟲師 #函數帶關鍵字參數 >>> def say(a=1,b=2): print a,b >>> def haha(**kw): apply(say,(),kw) >>> haha(a='a',b='b') a b
===================================
re.compile() 能夠把正則表達式編譯成一個正則表達式對象.
re.findall() 方法讀取html 中包含 imgre(正則表達式)的數據。
#coding=utf-8 import urllib import re def getHtml(url): page = urllib.urlopen(url) html = page.read() return html def getImg(html): reg = r'src="(.+?\.jpg)" pic_ext' imgre = re.compile(reg) imglist = re.findall(imgre,html) x = 0 for imgurl in imglist: urllib.urlretrieve(imgurl,'%s.jpg' % x) x+=1 html = getHtml("http://tieba.baidu.com/p/2460150866") print getImg(html)
=================================================
什麼是xml?
xml便可擴展標記語言,它能夠用來標記數據、定義數據類型,是一種容許用戶對本身的標記語言進行定義的源語言。
從結構上,它很像咱們常見的HTML超文本標記語言。但他們被設計的目的是不一樣的,超文本標記語言被設計用來顯示數據,其焦點是數據的外觀。它被設計用來傳輸和存儲數據,其焦點是數據的內容。
<aa>
<bb></bb>
</aa>