天天看點

Python學習筆記

目錄

一、安裝、編譯與運作

二、變量、運算與表達式

三、資料類型

      1、數字

      2、字元串

      3、元組

      4、清單

      5、字典

四、流程控制

      1、if-else

      2、for

      3、while

      4、switch

五、函數

      1、自定義函數

      2、Lambda函數

      3、Python内置函數

六、包與子產品

      1、子產品module

      2、包package

七、正規表達式

      1、元字元

      2、常用函數

      3、分組 

      4、一個小執行個體-爬蟲

八、深拷貝與淺拷貝

九、檔案與目錄

      1、檔案讀寫

      2、OS子產品

      3、目錄周遊

十、異常處理

       Python的安裝很容易,直接到官網:http://www.python.org/下載下傳安裝就可以了。Ubuntu一般都預安裝了。沒有的話,就可以#apt-get install python。Windows的話直接下載下傳msi包安裝即可。Python 程式是通過解釋器執行的,是以安裝後,可以看到Python提供了兩個解析器,一個是IDLE (Python GUI),一個是Python (command line)。前者是一個帶GUI界面的版本,後者實際上和在指令提示符下運作python是一樣的。運作解釋器後,就會有一個指令提示符>>>,在提示符後鍵入你的程式語句,鍵入的語句将會立即執行。就像Matlab一樣。

       另外,Matlab有.m的腳步檔案,python也有.py字尾的腳本檔案,這個檔案除了可以解釋執行外,還可以編譯運作,編譯後運作速度要比解釋運作要快。

       例如,我要列印一個helloWorld。

方法1:直接在解釋器中,>>> print ‘helloWorld’。

方法2:将這句代碼寫到一個檔案中,例如hello.py。運作這個檔案有三種方式:

1)在終端中:python hello.py

2)先編譯成.pyc檔案:

import py_compile

py_compile.compile("hello.py")

再在終端中:python hello.pyc

3)在終端中:

python -O -m py_compile hello.py

python hello.pyo

       編譯成.pyc和.pyo檔案後,執行的速度會更快。是以一般一些重複性并多次調用的代碼會被編譯成這兩種可執行的方式來待調用。

         這裡沒什麼好說的,有其他語言的程式設計基礎的話都沒什麼問題。和Matlab的相似度比較大。這塊差别不是很大。具體如下:

         需要注意的一個是:5/2 等于2,5.0/2才等于2.5。

[python] view plain copy

  1. ###################################  
  2. ### compute #######  
  3. # raw_input() get input from keyboard to string type  
  4. # So we should transfer to int type  
  5. # Some new support computing type:  
  6. # and or not in is < <= != == | ^ & << + - / % ~ **  
  7. print 'Please input a number:'  
  8. number = int(raw_input())   
  9. number += 1  
  10. print number**2 # ** means ^  
  11. print number and 1  
  12. print number or 1  
  13. print not number  
  14. 5/2 # is 2  
  15. 5.0/2 # is 2.5, should be noted  

1、數字

         通常的int, long,float,long等等都被支援。而且會看你的具體數字來定義變量的類型。如下:

  1. ### type of value #######  
  2. # int, long, float  
  3. # do not need to define the type of value, python will  
  4. # do this according to your value  
  5. num = 1   # stored as int type  
  6. num = 1111111111111   # stored as long int type  
  7. num = 1.0   # stored as float type  
  8. num = 12L # L stands for long type  
  9. num = 1 + 12j # j stands for complex type  
  10. num = '1' # string type  

2、字元串

         單引号,雙引号和三引号都可以用來定義字元串。三引号可以定義特别格式的字元串。字元串作為一種序列類型,支援像Matlab一樣的索引通路和切片通路。

  1. ### type of string #######  
  2. num = "1" # string type  
  3. num = "Let's go" # string type  
  4. num = "He's \"old\"" # string type  
  5. mail = "Xiaoyi: \n hello \n I am you!"  
  6. mail = """Xiaoyi: 
  7.     hello 
  8.     I am you! 
  9.     """ # special string format  
  10. string = 'xiaoyi' # get value by index  
  11. copy = string[0] + string[1] + string[2:6] # note: [2:6] means [2 5] or[2 6)  
  12. copy = string[:4] # start from 1  
  13. copy = string[2:] # to end  
  14. copy = string[::1] # step is 1, from start to end  
  15. copy = string[::2] # step is 2  
  16. copy = string[-1] # means 'i', the last one  
  17. copy = string[-4:-2:-1] # means 'yoa', -1 step controls direction  
  18. memAddr = id(num) # id(num) get the memory address of num  
  19. type(num) # get the type of num  

3、元組

         元組tuple用()來定義。相當于一個可以存儲不同類型資料的一個數組。可以用索引來通路,但需要注意的一點是,裡面的元素不能被修改。

  1. ### sequence type #######  
  2. ## can access the elements by index or slice  
  3. ## include: string, tuple(or array? structure? cell?), list  
  4. # basis operation of sequence type  
  5. firstName = 'Zou'  
  6. lastName = 'Xiaoyi'  
  7. len(string) # the length  
  8. name = firstName + lastName # concatenate 2 string  
  9. firstName * 3 # repeat firstName 3 times  
  10. 'Z' in firstName # check contain or not, return true  
  11. string = '123'  
  12. max(string)  
  13. min(string)  
  14. cmp(firstName, lastName) # return 1, -1 or 0  
  15. ## tuple(or array? structure? cell?)  
  16. ## define this type using ()  
  17. user = ("xiaoyi", 25, "male")  
  18. name = user[0]  
  19. age = user[1]  
  20. gender = user[2]  
  21. t1 = () # empty tuple  
  22. t2 = (2, ) # when tuple has only one element, we should add a extra comma  
  23. user[1] = 26 # error!! the elements can not be changed  
  24. name, age, gender = user # can get three element respectively  
  25. a, b, c = (1, 2, 3)  

4、清單

         清單list用[]來定義。它和元組的功能一樣,不同的一點是,裡面的元素可以修改。List是一個類,支援很多該類定義的方法,這些方法可以用來對list進行操作。

  1. ## list type (the elements can be modified)  
  2. ## define this type using []  
  3. userList = ["xiaoyi", 25, "male"]  
  4. name = userList[0]  
  5. age = userList[1]  
  6. gender = userList[2]  
  7. userList[3] = 88888 # error! access out of range, this is different with Matlab  
  8. userList.append(8888) # add new elements  
  9. "male" in userList # search  
  10. userList[2] = 'female' # can modify the element (the memory address not change)  
  11. userList.remove(8888) # remove element  
  12. userList.remove(userList[2]) # remove element  
  13. del(userList[1]) # use system operation api  
  14. ## help(list.append)  
  15. ################################  
  16. ######## object and class ######  
  17. ## object = property + method  
  18. ## python treats anything as class, here the list type is a class,  
  19. ## when we define a list "userList", so we got a object, and we use  
  20. ## its method to operate the elements  

5、字典

         字典dictionary用{}來定義。它的優點是定義像key-value這種鍵值對的結構,就像struct結構體的功能一樣。它也支援字典類支援的方法進行建立和操作。

Python學習筆記
  1. ######## dictionary type ######  
  2. ## define this type using {}  
  3. item = ['name', 'age', 'gender']  
  4. value = ['xiaoyi', '25', 'male']  
  5. zip(item, value) # zip() will produce a new list:   
  6. # [('name', 'xiaoyi'), ('age', '25'), ('gender', 'male')]  
  7. # but we can not define their corresponding relationship  
  8. # and we can define this relationship use dictionary type  
  9. # This can be defined as a key-value manner  
  10. # dic = {key1: value1, key2: value2, ...}, key and value can be any type  
  11. dic = {'name': 'xiaoyi', 'age': 25, 'gender': 'male'}  
  12. dic = {1: 'zou', 'age':25, 'gender': 'male'}  
  13. # and we access it like this: dic[key1], the key as a index  
  14. print dic['name']  
  15. print dic[1]  
  16. # another methods create dictionary  
  17. fdict = dict(['x', 1], ['y', 2]) # factory mode  
  18. ddict = {}.fromkeys(('x', 'y'), -1) # built-in mode, default value is the same which is none  
  19. # access by for circle  
  20. for key in dic  
  21.     print key  
  22.     print dic[key]  
  23. # add key or elements to dictionary, because dictionary is out of sequence,  
  24. # so we can directly and a key-value pair like this:  
  25. dic['tel'] = 88888    
  26. # update or delete the elements  
  27. del dic[1] # delete this key  
  28. dic.pop('tel') # show and delete this key  
  29. dic.clear() # clear the dictionary  
  30. del dic # delete the dictionary  
  31. dic.get(1) # get the value of key  
  32. dic.get(1, 'error') # return a user-define message if the dictionary do not contain the key  
  33. dic.keys()  
  34. dic.values()  
  35. dic.has_key(key)  
  36. # dictionary has many operations, please use help to check out  

         在這塊,Python與其它大多數語言有個非常不同的地方,Python語言使用縮進塊來表示程式邏輯(其它大多數語言使用大括号等)。例如:

if age < 21:

    print("你不能買酒。")

    print("不過你能買口香糖。")

print("這句話處于if語句塊的外面。")

         這個代碼相當于c語言的:

if (age < 21)

{

}

       可以看到,Python語言利用縮進表示語句塊的開始和退出(Off-side規則),而非使用花括号或者某種關鍵字。增加縮進表示語句塊的開始(注意前面有個:号),而減少縮進則表示語句塊的退出。根據PEP的規定,必須使用4個空格來表示每級縮進(不清楚4個空格的規定如何,在實際編寫中可以自定義空格數,但是要滿足每級縮進間空格數相等)。使用Tab字元和其它數目的空格雖然都可以編譯通過,但不符合編碼規範。

       為了使我們自己編寫的程式能很好的相容别人的程式,我們最好還是按規範來,用四個空格來縮減(注意,要麼都是空格,要是麼都制表符,千萬别混用)。

1、if-else

         If-else用來判斷一些條件,以執行滿足某種條件的代碼。

  1. ######## procedure control #####  
  2. ## if else  
  3. if expression: # bool type and do not forget the colon  
  4.     statement(s) # use four space key   
  5. if expression:   
  6. statement(s) # error!!!! should use four space key   
  7. if 1<2:  
  8.     print 'ok, ' # use four space key  
  9.     print 'yeah' # use the same number of space key  
  10. if True: # true should be big letter True  
  11.     print 'true'  
  12. def fun():  
  13.     return 1  
  14. if fun():  
  15.     print 'ok'  
  16. else:  
  17.     print 'no'  
  18. con = int(raw_input('please input a number:'))  
  19. if con < 2:  
  20.     print 'small'  
  21. elif con > 3:  
  22.     print 'big'  
  23.     print 'middle'  
  24. if 1 < 2:  
  25.     if 2 < 3:  
  26.         print 'yeah'  
  27.     else:  
  28.         print 'no'    
  29.     print 'out'  
  30.     print 'bad'  
  31. if 1<2 and 2<3 or 2 < 4 not 0: # and, or, not  
  32.     print 'yeah'  

2、for

         for的作用是循環執行某段代碼。還可以用來周遊我們上面所提到的序列類型的變量。

  1. ## for  
  2. for iterating_val in sequence:  
  3.     statements(s)  
  4. # sequence type can be string, tuple or list  
  5. for i in "abcd":  
  6.     print i  
  7. for i in [1, 2, 3, 4]:  
  8. # range(start, end, step), if not set step, default is 1,   
  9. # if not set start, default is 0, should be noted that it is [start, end), not [start, end]  
  10. range(5) # [0, 1, 2, 3, 4]  
  11. range(1, 5) # [1, 2, 3, 4]  
  12. range(1, 10, 2) # [1, 3, 5, 7, 9]  
  13. for i in range(1, 100, 1):   
  14. # ergodic for basis sequence  
  15. fruits = ['apple', 'banana', 'mango']  
  16. for fruit in range(len(fruits)):   
  17.     print 'current fruit: ', fruits[fruit]  
  18. # ergodic for dictionary  
  19. dic = {1: 111, 2: 222, 5: 555}  
  20. for x in dic:  
  21.     print x, ': ', dic[x]  
  22. dic.items() # return [(1, 111), (2, 222), (5, 555)]  
  23. for key,value in dic.items(): # because we can: a,b=[1,2]  
  24.     print key, ': ', value  
  25.     print 'ending'  
  26. import time  
  27. # we also can use: break, continue to control process  
  28. for x in range(1, 11):  
  29.     print x  
  30.     time.sleep(1) # sleep 1s  
  31.     if x == 3:  
  32.         pass # do nothing  
  33.     if x == 2:  
  34.         continue  
  35.     if x == 6:  
  36.         break  
  37.     if x == 7:    
  38.         exit() # exit the whole program  
  39.     print '#'*50  

3、while

         while的用途也是循環。它首先檢查在它後邊的循環條件,若條件表達式為真,它就執行冒号後面的語句塊,然後再次測試循環條件,直至為假。冒号後面的縮近語句塊為循環體。

  1. ## while  
  2. while expression:  
  3.     statement(s)  
  4. while True:  
  5.     print 'hello'  
  6.     x = raw_input('please input something, q for quit:')  
  7.     if x == 'q':  

4、switch

         其實Python并沒有提供switch結構,但我們可以通過字典和函數輕松的進行構造。例如:

  1. #############################  
  2. ## switch ####  
  3. ## this structure do not support by python  
  4. ## but we can implement it by using dictionary and function  
  5. ## cal.py ##  
  6. #!/usr/local/python  
  7. from __future__ import division  
  8. # if used this, 5/2=2.5, 6/2=3.0  
  9. def add(x, y):  
  10.     return x + y  
  11. def sub(x, y):  
  12.     return x - y  
  13. def mul(x, y):  
  14.     return x * y  
  15. def div(x, y):  
  16.     return x / y  
  17. operator = {"+": add, "-": sub, "*": mul, "/": div}  
  18. operator["+"](1, 2) # the same as add(1, 2)  
  19. operator["%"](1, 2) # error, not have key "%", but the below will not  
  20. operator.get("+")(1, 2) # the same as add(1, 2)  
  21. def cal(x, o, y):  
  22.     print operator.get(o)(x, y)  
  23. cal(2, "+", 3)  
  24. # this method will effect than if-else  

1、自定義函數

         在Python中,使用def語句來建立函數:

  1. ######## function #####   
  2. def functionName(parameters): # no parameters is ok  
  3.     bodyOfFunction  
  4. def add(a, b):  
  5.     return a+b # if we do not use a return, any defined function will return default None   
  6. a = 100  
  7. b = 200  
  8. sum = add(a, b)  
  9. ##### function.py #####  
  10. #!/usr/bin/python  
  11. #coding:utf8  # support chinese  
  12. def add(a = 1, b = 2): # default parameters  
  13.     return a+b  # can return any type of data  
  14. # the followings are all ok  
  15. add()  
  16. add(2)  
  17. add(y = 1)  
  18. add(3, 4)  
  19. ###### the global and local value #####  
  20. ## global value: defined outside any function, and can be used  
  21. ##              in anywhere, even in functions, this should be noted  
  22. ## local value: defined inside a function, and can only be used  
  23. ##              in its own function  
  24. ## the local value will cover the global if they have the same name  
  25. val = 100 # global value  
  26.     print val # here will access the val = 100  
  27. print val # here will access the val = 100, too  
  28.     a = 100 # local value  
  29.     print a  
  30. print a # here can not access the a = 100  
  31.     global a = 100 # declare as a global value  
  32. print a # here can not access the a = 100, because fun() not be called yet  
  33. fun()  
  34. print a # here can access the a = 100  
  35. ############################  
  36. ## other types of parameters  
  37. def fun(x):  
  38. # the follows are all ok  
  39. fun(10) # int  
  40. fun('hello') # string  
  41. fun(('x', 2, 3))  # tuple  
  42. fun([1, 2, 3])    # list  
  43. fun({1: 1, 2: 2}) # dictionary  
  44. ## tuple  
  45. def fun(x, y):  
  46.     print "%s : %s" % (x,y) # %s stands for string  
  47. fun('Zou', 'xiaoyi')  
  48. tu = ('Zou', 'xiaoyi')  
  49. fun(*tu)    # can transfer tuple parameter like this  
  50. ## dictionary  
  51. def fun(name = "name", age = 0):  
  52.     print "name: %s" % name  
  53.     print "age: " % age  
  54. dic = {name: "xiaoyi", age: 25} # the keys of dictionary should be same as fun()  
  55. fun(**dic) # can transfer dictionary parameter like this  
  56. fun(age = 25, name = 'xiaoyi') # the result is the same  
  57. ## the advantage of dictionary is can specify value name  
  58. ## redundancy parameters ####  
  59. ## the tuple  
  60. def fun(x, *args): # the extra parameters will stored in args as tuple type   
  61.     print args  
  62. # the follows are ok  
  63. fun(10)  
  64. fun(10, 12, 24) # x = 10, args = (12, 24)  
  65. ## the dictionary  
  66. def fun(x, **args): # the extra parameters will stored in args as dictionary type   
  67. fun(x = 10, y = 12, z = 15) # x = 10, args = {'y': 12, 'z': 15}  
  68. # mix of tuple and dictionary  
  69. def fun(x, *args, **kwargs):  
  70.     print kwargs  
  71. fun(1, 2, 3, 4, y = 10, z = 12) # x = 1, args = (2, 3, 4), kwargs = {'y': 10, 'z': 12}  

2、Lambda函數

         Lambda函數用來定義一個單行的函數,其便利在于:

  1. ## lambda function ####  
  2. ## define a fast single line function  
  3. fun = lambda x,y : x*y # fun is a object of function class  
  4. fun(2, 3)  
  5. # like  
  6.     return x*y  
  7. ## recursion  
  8. # 5=5*4*3*2*1, n!  
  9. def recursion(n):  
  10.     if n > 0:  
  11.         return n * recursion(n-1) ## wrong  
  12. numList = range(1, 5)  
  13. reduce(mul, numList) # 5! = 120  
  14. reduce(lambda x,y : x*y, numList) # 5! = 120, the advantage of lambda function avoid defining a function  
  15. ### list expression  
  16. numList = [1, 2, 6, 7]  
  17. filter(lambda x : x % 2 == 0, numList)  
  18. print [x for x in numList if x % 2 == 0] # the same as above  
  19. map(lambda x : x * 2 + 10, numList)  
  20. print [x * 2 + 10 for x in numList] # the same as above  

3、Python内置函數

       Python内置了很多函數,他們都是一個個的.py檔案,在python的安裝目錄可以找到。弄清它有那些函數,對我們的高效程式設計非常有用。這樣就可以避免重複的勞動了。下面也隻是列出一些常用的:

    1. ## built-in function of python ####  
    2. ## if do not how to use, please use help()  
    3. abs, max, min, len, divmod, pow, round, callable,  
    4. isinstance, cmp, range, xrange, type, id, int()  
    5. list(), tuple(), hex(), oct(), chr(), ord(), long()  
    6. callable # test a function whether can be called or not, if can, return true  
    7. # or test a function is exit or not  
    8. isinstance # test type  
    9. numList = [1, 2]  
    10. if type(numList) == type([]):  
    11.     print "It is a list"  
    12. if isinstance(numList, list): # the same as above, return true  
    13. for i in range(1, 10001) # will create a 10000 list, and cost memory  
    14. for i in xrange(1, 10001)# do not create such a list, no memory is cost  
    15. ## some basic functions about string  
    16. str = 'hello world'  
    17. str.capitalize() # 'Hello World', first letter transfer to big  
    18. str.replace("hello", "good") # 'good world'  
    19. ip = "192.168.1.123"  
    20. ip.split('.') # return ['192', '168', '1', '123']  
    21. help(str.split)  
    22. import string  
    23. string.replace(str, "hello", "good") # 'good world'  
    24. ## some basic functions about sequence  
    25. len, max, min  
    26. # filter(function or none, sequence)  
    27.     if x > 5:  
    28.         return True  
    29. filter(fun, numList) # get [6, 7], if fun return True, retain the element, otherwise delete it  
    30. # zip()  
    31. name = ["me", "you"]  
    32. age = [25, 26]  
    33. tel = ["123", "234"]  
    34. zip(name, age, tel) # return a list: [('me', 25, '123'), ('you', 26, '234')]  
    35. # map()  
    36. map(None, name, age, tel) # also return a list: [('me', 25, '123'), ('you', 26, '234')]  
    37. test = ["hello1", "hello2", "hello3"]  
    38. zip(name, age, tel, test) # return [('me', 25, '123', 'hello1'), ('you', 26, '234', 'hello2')]  
    39. map(None, name, age, tel, test) # return [('me', 25, '123', 'hello1'), ('you', 26, '234', 'hello2'), (None, None, None, 'hello3')]  
    40. a = [1, 3, 5]  
    41. b = [2, 4, 6]  
    42. map(mul, a, b) # return [2, 12, 30]  
    43. # reduce()  
    44. reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) # return ((((1+2)+3)+4)+5)  

正規表達式:

Python學習筆記