Python基礎知識


一、安裝、編譯與運行

       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等等都被支持。而且會看你的具體數字來定義變量的類型。如下:

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

2、字符串

         單引號,雙引號和三引號都可以用來定義字符串。三引號可以定義特別格式的字符串。字符串作爲一種序列類型,支持像Matlab一樣的索引訪問和切片訪問。

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

3、元組

         元組tuple用()來定義。相當於一個可以存儲不同類型數據的一個數組。可以用索引來訪問,但需要注意的一點是,裏面的元素不能被修改。

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

4、列表

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

[python] view plain copy
  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. ################################  
  17. ######## object and class ######  
  18. ## object = property + method  
  19. ## python treats anything as class, here the list type is a class,  
  20. ## when we define a list "userList", so we got a object, and we use  
  21. ## its method to operate the elements  

5、字典

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

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

四、流程控制

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

if age < 21:

    print("你不能買酒。")

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

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

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

if (age < 21)

{

    print("你不能買酒。")

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

}

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

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

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

1、if-else

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

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

2、for

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

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

3、while

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

[python] view plain copy
  1. ################################  
  2. ######## procedure control #####  
  3. ## while  
  4. while expression:  
  5.     statement(s)  
  6.   
  7. while True:  
  8.     print 'hello'  
  9.     x = raw_input('please input something, q for quit:')  
  10.     if x == 'q':  
  11.         break  
  12. else:  
  13.     print 'ending'  

4、switch

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

[python] view plain copy
  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.   
  8. from __future__ import division  
  9. # if used this, 5/2=2.5, 6/2=3.0  
  10.   
  11. def add(x, y):  
  12.     return x + y  
  13. def sub(x, y):  
  14.     return x - y  
  15. def mul(x, y):  
  16.     return x * y  
  17. def div(x, y):  
  18.     return x / y  
  19.   
  20. operator = {"+": add, "-": sub, "*": mul, "/": div}  
  21. operator["+"](12# the same as add(1, 2)  
  22. operator["%"](12# error, not have key "%", but the below will not  
  23. operator.get("+")(12# the same as add(1, 2)  
  24.   
  25. def cal(x, o, y):  
  26.     print operator.get(o)(x, y)  
  27. cal(2"+"3)  
  28. # this method will effect than if-else  


五、函數

1、自定義函數

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

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

2、Lambda函數

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

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

3、Python內置函數

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

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

六、包與模塊

1、模塊module

         python中每一個.py腳本定義一個模塊,所以我們可以在一個.py腳本中定義一個實現某個功能的函數或者腳本,這樣其他的.py腳本就可以調用這個模塊了。調用的方式有三種,如下:

[python] view plain copy
  1. ###################################  
  2. ## package and module ####  
  3. ## a .py file define a module which can be used in other script  
  4. ## as a script, the name of module is the same as the name of the .py file  
  5. ## and we use the name to import to a new script  
  6. ## e.g., items.py, import items  
  7. ## python contains many .py files, which we can import and use  
  8. # vi cal.py  
  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.   
  18. print "Your answer is: ", add(35)  
  19.   
  20. if __name__ == "__main__"  
  21.     r = add(13)  
  22.     print r  
  23.       
  24. # vi test.py  
  25. import cal # will expand cal.py here  
  26. # so, this will execute the following code in cal.py  
  27. # print "Your answer is: ", add(3, 5)  
  28. # it will print "Your answer is: 8"  
  29. # but as we import cal.py, we just want to use those functions  
  30. # so the above code can do this for me, the r=add(1, 3) will not execute  
  31. result = cal.add(12)  
  32. print result  
  33. # or  
  34. import cal as c  
  35. result = c.add(12)  
  36. # or  
  37. from cal import add  
  38. result = add(12)  

2、包package

       python 的每個.py文件執行某種功能,那有時候我們需要多個.py完成某個更大的功能,或者我們需要將同類功能的.py文件組織到一個地方,這樣就可以很方便我們的使用。模塊可以按目錄組織爲包,創建一個包的步驟:

# 1、建立一個名字爲包名字的文件夾

# 2、在該文件夾下創建一個__init__.py空文件

# 3、根據需要在該文件夾下存放.py腳本文件、已編譯拓展及子包

# 4、import pack.m1,pack.m2 pack.m3

[python] view plain copy
  1. #### package 包  
  2. ## python 的模塊可以按目錄組織爲包,創建一個包的步驟:  
  3. # 1、建立一個名字爲包名字的文件夾  
  4. # 2、在該文件夾下創建一個__init__.py 空文件  
  5. # 3、根據需要在該文件夾下存放.py腳本文件、已編譯拓展及子包  
  6. # 4、import pack.m1, pack.m2 pack.m3  
  7. mkdir calSet  
  8. cd calSet  
  9. touch __init_.py  
  10. cp cal.py .  
  11.   
  12. # vi test.py  
  13. import calSet.cal  
  14. result = calSet.cal.add(12)  
  15. print result  

七、正則表達式

       正則表達式,(英語:RegularExpression,在代碼中常簡寫爲regex、regexp或RE),計算機科學的一個概念。正則表達式使用單個字符串來描述、匹配一系列符合某個句法規則的字符串。在很多文本編輯器裏,正則表達式通常被用來檢索、替換那些符合某個模式的文本。

         Python提供了功能強大的正則表達式引擎re,我們可以利用這個模塊來利用正則表達式進行字符串操作。我們用import re來導入這個模塊。

         正則表達式包含了很多規則,如果能靈活的使用,在匹配字符串方面是非常高效率的。更多的規則,我們需要查閱其他的資料。

1、元字符

         很多,一些常用的元字符的使用方法如下:

[python] view plain copy
  1. ##############################  
  2. ## 正則表達式 RE  
  3. ## re module in python  
  4. import re  
  5. rule = r'abc' # r prefix, the rule you want to check in a given string  
  6. re.findall(rule, "aaaaabcaaaaaabcaa"# return ['abc', 'abc']  
  7.   
  8. # [] 用來指定一個字符集 [abc] 表示 abc其中任意一個字符符合都可以  
  9. rule = r"t[io]p"   
  10. re.findall(rule, "tip tep twp top"# return ['tip', 'top']  
  11.   
  12. # ^ 表示 補集,例如[^io] 表示除i和o外的其他字符  
  13. rule = r"t[^io]p"   
  14. re.findall(rule, "tip tep twp top"# return ['tep', 'twp']  
  15.   
  16. # ^ 也可以 匹配行首,表示要在行首才匹配,其他地方不匹配  
  17. rule = r"^hello"  
  18. re.findall(rule, "hello tep twp hello"# return ['hello']  
  19. re.findall(rule, "tep twp hello"# return []  
  20.   
  21. # $ 表示匹配行尾  
  22. rule = r"hello$"  
  23. re.findall(rule, "hello tep twp hello"# return ['hello']  
  24. re.findall(rule, "hello tep twp"# return []  
  25.   
  26. # - 表示範圍  
  27. rule = r"x[0123456789]x" # the same as  
  28. rule = r"x[0-9]x"  
  29. re.findall(rule, "x1x x4x xxx"# return ['x1x', 'x4x']  
  30. rule = r"x[a-zA-Z]x"  
  31.   
  32. # \ 表示轉義符  
  33. rule = r"\^hello"  
  34. re.findall(rule, "hello twp ^hello"# return ['^hello']  
  35. # \d 匹配一個數字字符。等價於[0-9]。  
  36. # \D 匹配一個非數字字符。等價於[^0-9]。  
  37. # \n 匹配一個換行符。等價於\x0a和\cJ。  
  38. # \r 匹配一個回車符。等價於\x0d和\cM。  
  39. # \s 匹配任何空白字符,包括空格、製表符、換頁符等等。等價於[ \f\n\r\t\v]。  
  40. # \S 匹配任何非空白字符。等價於[^ \f\n\r\t\v]。  
  41. # \t 匹配一個製表符。等價於\x09和\cI。  
  42. # \w 匹配包括下劃線的任何單詞字符。等價於“[A-Za-z0-9_]”。  
  43. # \W 匹配任何非單詞字符。等價於“[^A-Za-z0-9_]”。  
  44.   
  45. # {} 表示重複規則  
  46. # 例如我們要查找匹配是否是 廣州的號碼,020-八位數據  
  47. # 以下三種方式都可以實現  
  48. rule = r"^020-\d\d\d\d\d\d\d\d$"  
  49. rule = r"^020-\d{8}$" # {8} 表示前面的規則重複8次  
  50. rule = r"^020-[0-9]{8}$"  
  51. re.findall(rule, "020-23546813"# return ['020-23546813']  
  52.   
  53. # * 表示將其前面的字符重複0或者多次  
  54. rule = r"ab*"  
  55. re.findall(rule, "a"# return ['a']  
  56. re.findall(rule, "ab"# return ['ab']  
  57.   
  58. # + 表示將其前面的字符重複1或者多次  
  59. rule = r"ab+"  
  60. re.findall(rule, "a"# return []  
  61. re.findall(rule, "ab"# return ['ab']  
  62. re.findall(rule, "abb"# return ['abb']  
  63.   
  64. # ? 表示前面的字符可有可無  
  65. rule = r"^020-?\d{8}$"  
  66. re.findall(rule, "02023546813"# return ['020-23546813  
  67. re.findall(rule, "020-23546813"# return ['020-23546813']  
  68. re.findall(rule, "020--23546813"# return []  
  69.   
  70. # ? 表示非貪婪匹配  
  71. rule = r"ab+?"  
  72. re.findall(rule, "abbbbbbb"# return ['ab']  
  73.   
  74. # {} 可以表示範圍  
  75. rule = r"a{1,3}"  
  76. re.findall(rule, "a"# return ['a']  
  77. re.findall(rule, "aa"# return ['aa']  
  78. re.findall(rule, "aaa"# return ['aaa']  
  79. re.findall(rule, "aaaa"# return ['aaa', 'a']  
  80.   
  81. ## compile re string  
  82. rule = r"\d{3,4}-?\d{8}"  
  83. re.findall(rule, "020-23546813")  
  84. # faster when you compile it  
  85. # return a object  
  86. p_tel = re.compile(rule)  
  87. p_tel.findall("020-23546813")  
  88.   
  89. # the parameter re.I 不區分大小寫  
  90. name_re = re.compile(r"xiaoyi", re.I)  
  91. name_re.findall("Xiaoyi")  
  92. name_re.findall("XiaoYi")  
  93. name_re.findall("xiAOyi")  


2、常用函數

         Re模塊作爲一個對象,它還支持很多的操作,例如:

[python] view plain copy
  1. # the object contain some methods we can use  
  2. # match 去搜索字符串開頭,如果匹配對,那就返回一個對象,否則返回空  
  3. obj = name_re.match('Xiaoyi, Zou')  
  4. # search 去搜索字符串(任何位置),如果匹配對,那就返回一個對象  
  5. obj = name_re.search('Zou, Xiaoyi')  
  6. # 然後可以用它來進行判斷某字符串是否存在我們的正則表達式  
  7. if obj:  
  8.     pass  
  9. # findall 返回一個滿足正則的列表  
  10. name_re.findall("Xiaoyi")  
  11.   
  12. # finditer 返回一個滿足正則的迭代器  
  13. name_re.finditer("Xiaoyi")  
  14.   
  15. # 正則替換  
  16. rs = r"z..x"  
  17. re.sub(rs, 'python''zoux ni ziox me'# return 'python ni python me'  
  18. re.subn(rs, 'python''zoux ni ziox me'# return ('python ni python me', 2), contain a number  
  19.   
  20. # 正則切片  
  21. str = "123+345-32*78"  
  22. re.split(r'[\+\-\*]', str) # return ['123', '345', '32', '78']  
  23.   
  24. # 可以打印re模塊支持的屬性和方法,然後用help  
  25. dir(re)  
  26.   
  27. ##### 編譯正則表達式式 可以加入一些屬性,可以增加很多功能  
  28. # 多行匹配  
  29. str = """ 
  30.     hello xiaoyi 
  31.     xiaoyi hello 
  32.     hello zou 
  33.     xiaoyi hello 
  34.     """  
  35. re.findall(r'xiaoyi', str, re.M)  

3、分組

         分組有兩個作用,它用()來定義一個組,組內的規則只對組內有效。

[python] view plain copy
  1. # () 分組  
  2. email = r"\w{3}@\w+(\.com|\.cn|\.org)"    
  3. re.match(email, "[email protected]")  
  4. re.match(email, "[email protected]")  
  5. re.match(email, "[email protected]")  

    另外,分組可以優先返回分組內匹配的字符串。

[python] view plain copy
  1. # 另外,分組可以優先返回分組內匹配的字符串  
  2. str = """ 
  3.     idk hello name=zou yes ok d 
  4.     hello name=xiaoyi yes no dksl 
  5.     dfi lkasf dfkdf hello name=zouxy yes d 
  6.     """  
  7. r1 = r"hello name=.+ yes"  
  8. re.findall(r1, str) # return ['hello name=zou yes', 'hello name=xiaoyi yes', 'hello name=zouxy yes']  
  9. r2 = r"hello name=(.+) yes"  
  10. re.findall(r2, str) # return ['zou', 'xiaoyi', 'zouxy']  
  11. # 可以看到,它會匹配整個正則表達式,但只會返回()括號分組內的字符串,  
  12. # 用這個屬性,我們就可以進行爬蟲,抓取一些想要的數據  

4、一個小實例-爬蟲

         這個實例利用上面的正則和分組的優先返回特性來實現一個小爬蟲算法。它的功能是到一個給定的網址裏面將.jpg後綴的圖片全部下載下來。

[python] view plain copy
  1. ## 一個小爬蟲  
  2. ## 下載貼吧 或 空間中的所有圖片  
  3. ## getJpg.py  
  4.   
  5. #!/usr/bin/python  
  6. import re  
  7. import urllib  
  8.   
  9. # Get the source code of a website  
  10. def getHtml(url):  
  11.     print 'Getting html source code...'  
  12.     page = urllib.open(url)  
  13.     html = page.read()  
  14.     return html  
  15.   
  16. # Open the website and check up the address of images,  
  17. # and find the common features to decide the re_rule  
  18. def getImageAddrList(html):  
  19.     print 'Getting all address of images...'  
  20.     rule = r"src=\"(.+\.jpg)\" pic_ext"  
  21.     imReg = re.compile(rule)  
  22.     imList = re.findall(imReg, html)  
  23.     return imList  
  24.   
  25. def getImage(imList):  
  26.     print 'Downloading...'  
  27.     name = 1;  
  28.     for imgurl in imList:  
  29.         urllib.urlretrieve(imgurl, '%s.jpg' % name)  
  30.         name += 1  
  31.     print 'Got ', len(imList), ' images!'  
  32.   
  33. ## main  
  34. htmlAddr = "http://tieba.baidu.com/p/2510089409"  
  35. html = getHtml(htmlAddr)  
  36. imList = getImageAddrList(html)  
  37. getImage(imList)  

八、深拷貝與淺拷貝

Python中對數據的複製有兩個需要注意的差別:

淺拷貝:對引用對象的拷貝(只拷貝父對象),深拷貝:對對象資源的拷貝。具體的差別如下:

[python] view plain copy
  1. ##############################  
  2. ### memory operation  
  3. ## 淺拷貝:對引用對象的拷貝(只拷貝父對象)  
  4. ## 深拷貝:對對象資源的拷貝  
  5.   
  6. a = [123]  
  7. b = a # id(a) == id (b), 同一個標籤,相當於引用  
  8. a.append(4# a = [1, 2, 3, 4], and b also change to = [1, 2, 3, 4]  
  9.   
  10. import copy  
  11. a = [12, ['a''b']] # 二元列表  
  12. c = copy.copy(a)  # id(c) != id(a)  
  13. a.append('d'# a = [1, 2, ['a', 'b'], 'd'] but c keeps not changed  
  14. # 但只屬於淺拷貝,只拷貝父對象  
  15. # 所以 id(a[0]) == id(c[0]),也就是說對a追加的元素不影響c,  
  16. # 但修改a被拷貝的數據後,c的對應數據也會改變,因爲拷貝不會改變元素的地址  
  17. a[2].append('d'# will change c, too  
  18. a[1] = 3 # will change c, too  
  19.   
  20. # 深拷貝  
  21. d = copy.deepcopy(a) # 全部拷貝,至此恩斷義絕,兩者各走  
  22. # 各的陽關道和獨木橋,以後毫無瓜葛  

九、文件與目錄

1、文件讀寫

        Python的文件操作和其他的語言沒有太大的差別。通過open或者file類來訪問。但python支持了很多的方法,以支持文件內容和list等類型的交互。具體如下:

[python] view plain copy
  1. ########################  
  2. ## file and directory  
  3. # file_handler = open(filename, mode)  
  4. # mode is the same as other program langurage  
  5. ## read  
  6. # method 1  
  7. fin = open('./test.txt')  
  8. fin.read()  
  9. fin.close()  
  10.   
  11. # method 2, class file  
  12. fin = file('./test.txt')  
  13. fin.read()  
  14. fin.close()  
  15.   
  16. ## write  
  17. fin = open('./test.txt''r+'# r, r+, w, w+, a, a+, b, U  
  18. fin.write('hello')  
  19. fin.close()  
  20.   
  21. ### 文件對象的方法  
  22. ## help(file)  
  23.   
  24. for i in open('test.txt'):  
  25.     print i  
  26.   
  27. str = fin.readline() # 每次讀取一行  
  28. list = fin.readlines() # 讀取多行,返回一個列表,每行作爲列表的一個元素  
  29. fin.next() # 讀取改行,指向下一行  
  30.   
  31. # 用列表來寫入多行  
  32. fin.writelines(list)  
  33.   
  34. # 移動指針  
  35. fin.seek(00)  
  36. fin.seek(01)  
  37. fin.seek(-12)  
  38.   
  39. # 提交更新  
  40. fin.flush() # 平時寫數據需要close才真正寫入文件,這個函數可以立刻寫入文件  


2、OS模塊

         os模塊提供了很多對系統的操作。例如對目錄的操作等。我們需要用import os來插入這個模塊以便使用。

[python] view plain copy
  1. #########################  
  2. ## OS module  
  3. ## directory operation should import this  
  4. import os  
  5.   
  6. os.mkdir('xiaoyi'# mkdir  
  7. os.makedirs('a/b/c', mode = 666# 創建分級的目錄  
  8. os.listdir() # ls 返回當前層所有文件或者文件夾名到一個列表中(不包括子目錄)  
  9. os.chdir() # cd  
  10. os.getcwd() # pwd  
  11. os.rmdir() # rm  


3、目錄遍歷

       目錄遍歷的實現可以做很多普遍的功能,例如殺毒軟件,垃圾清除軟件,文件搜索軟件等等。因爲他們都涉及到了掃描某目錄下所有的包括子目錄下的文件。所以需要對目錄進行遍歷。在這裏我們可以使用兩種方法對目錄進行遍歷:

1)遞歸

[python] view plain copy
  1. #!/usr/bin/python  
  2. #coding:utf8  
  3. import os  
  4.   
  5. def dirList(path):  
  6.     fileList = os.listdir(path)  
  7.     allFile = []  
  8.     for fileName in fileList:  
  9.         # allFile.append(dirPath + '/' + fileName) # the same as below  
  10.         filePath = os.path.join(path, fileName)  
  11.         if os.path.isdir(filePath):  
  12.             dirList(filePath)  
  13.         allFile.append(filePath)  
  14.     return allFile  

2)os.walk函數

[python] view plain copy
  1. # os.walk 返回一個生成器,每次是一個三元組 [目錄, 子目錄, 文件]  
  2. gen = os.walk('/')  
  3. for path, dir, filelist in os.walk('/'):  
  4.     for filename in filelist:  
  5.         os.path.join(path, filename)  

十、異常處理

      異常意味着錯誤,未經處理的異常會中止程序運行。而異常拋出機制,爲程序開發人員提供一種在運行時發現錯誤,並進行恢復處理,然後繼續執行的能力。

[python] view plain copy
  1. ###################################  
  2. ### 異常處理  
  3. # 異常拋出機制,爲程序開發人員提供一種在運行時發現錯誤,  
  4. # 進行恢復處理,然後繼續執行的能力  
  5.   
  6. # 用try去嘗試執行一些代碼,如果錯誤,就拋出異常,  
  7. # 異常由except來捕獲,並由我們寫代碼來處理這種異常  
  8. try:  
  9.     fin = open("abc.txt")  
  10.     print hello  
  11.     ### your usually process code here  
  12. except IOError, msg:  
  13.     print "On such file!"  
  14.     ### your code to handle this error  
  15. except NameError, msg:  
  16.     print msg  
  17.     ### your code to handle this error  
  18. finally# 不管上面有沒有異常,這個代碼塊都會被執行  
  19.     print 'ok'  
  20.   
  21. # 拋出異常,異常類型要滿足python內定義的  
  22. if filename == "hello":  
  23.     raise TypeError("Nothing!!")  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章