一、安裝、編譯與運行
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。
-
-
-
-
-
-
-
print 'Please input a number:'
-
number = int(raw_input())
-
number += 1
-
print number**2
-
print number and 1
-
print number or 1
-
print not number
-
5/2
-
5.0/2
三、數據類型
1、數字
通常的int, long,float,long等等都被支持。而且會看你的具體數字來定義變量的類型。如下:
-
-
-
-
-
-
num = 1
-
num = 1111111111111
-
num = 1.0
-
num = 12L
-
num = 1 + 12j
-
num = '1'
2、字符串
單引號,雙引號和三引號都可以用來定義字符串。三引號可以定義特別格式的字符串。字符串作爲一種序列類型,支持像Matlab一樣的索引訪問和切片訪問。
-
-
-
num = "1"
-
num = "Let's go"
-
num = "He's \"old\""
-
mail = "Xiaoyi: \n hello \n I am you!"
-
mail =
-
-
-
-
string = 'xiaoyi'
-
copy = string[0] + string[1] + string[2:6]
-
copy = string[:4]
-
copy = string[2:]
-
copy = string[::1]
-
copy = string[::2]
-
copy = string[-1]
-
copy = string[-4:-2:-1]
-
memAddr = id(num)
-
type(num)
3、元組
元組tuple用()來定義。相當於一個可以存儲不同類型數據的一個數組。可以用索引來訪問,但需要注意的一點是,裏面的元素不能被修改。
-
-
-
-
-
-
firstName = 'Zou'
-
lastName = 'Xiaoyi'
-
len(string)
-
name = firstName + lastName
-
firstName * 3
-
'Z' in firstName
-
string = '123'
-
max(string)
-
min(string)
-
cmp(firstName, lastName)
-
-
-
-
user = ("xiaoyi", 25, "male")
-
name = user[0]
-
age = user[1]
-
gender = user[2]
-
t1 = ()
-
t2 = (2, )
-
user[1] = 26
-
name, age, gender = user
-
a, b, c = (1, 2, 3)
4、列表
列表list用[]來定義。它和元組的功能一樣,不同的一點是,裏面的元素可以修改。List是一個類,支持很多該類定義的方法,這些方法可以用來對list進行操作。
-
-
-
userList = ["xiaoyi", 25, "male"]
-
name = userList[0]
-
age = userList[1]
-
gender = userList[2]
-
userList[3] = 88888
-
userList.append(8888)
-
"male" in userList
-
userList[2] = 'female'
-
userList.remove(8888)
-
userList.remove(userList[2])
-
del(userList[1])
-
-
-
-
-
-
-
-
5、字典
字典dictionary用{}來定義。它的優點是定義像key-value這種鍵值對的結構,就像struct結構體的功能一樣。它也支持字典類支持的方法進行創建和操作。
-
-
-
-
item = ['name', 'age', 'gender']
-
value = ['xiaoyi', '25', 'male']
-
zip(item, value)
-
-
-
-
-
-
dic = {'name': 'xiaoyi', 'age': 25, 'gender': 'male'}
-
dic = {1: 'zou', 'age':25, 'gender': 'male'}
-
-
print dic['name']
-
print dic[1]
-
-
fdict = dict(['x', 1], ['y', 2])
-
ddict = {}.fromkeys(('x', 'y'), -1)
-
-
for key in dic
-
print key
-
print dic[key]
-
-
-
-
dic['tel'] = 88888
-
-
del dic[1]
-
dic.pop('tel')
-
dic.clear()
-
del dic
-
dic.get(1)
-
dic.get(1, 'error')
-
dic.keys()
-
dic.values()
-
dic.has_key(key)
-
四、流程控制
在這塊,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用來判斷一些條件,以執行滿足某種條件的代碼。
-
-
-
-
if expression:
-
statement(s)
-
-
if expression:
-
statement(s)
-
-
if 1<2:
-
print 'ok, '
-
print 'yeah'
-
-
if True:
-
print 'true'
-
-
def fun():
-
return 1
-
-
if fun():
-
print 'ok'
-
else:
-
print 'no'
-
-
con = int(raw_input('please input a number:'))
-
if con < 2:
-
print 'small'
-
elif con > 3:
-
print 'big'
-
else:
-
print 'middle'
-
-
if 1 < 2:
-
if 2 < 3:
-
print 'yeah'
-
else:
-
print 'no'
-
print 'out'
-
else:
-
print 'bad'
-
-
if 1<2 and 2<3 or 2 < 4 not 0:
-
print 'yeah'
2、for
for的作用是循環執行某段代碼。還可以用來遍歷我們上面所提到的序列類型的變量。
-
-
-
-
for iterating_val in sequence:
-
statements(s)
-
-
-
for i in "abcd":
-
print i
-
-
for i in [1, 2, 3, 4]:
-
print i
-
-
-
-
range(5)
-
range(1, 5)
-
range(1, 10, 2)
-
for i in range(1, 100, 1):
-
print i
-
-
-
fruits = ['apple', 'banana', 'mango']
-
for fruit in range(len(fruits)):
-
print 'current fruit: ', fruits[fruit]
-
-
-
dic = {1: 111, 2: 222, 5: 555}
-
for x in dic:
-
print x, ': ', dic[x]
-
-
dic.items()
-
for key,value in dic.items():
-
print key, ': ', value
-
else:
-
print 'ending'
-
-
-
import time
-
-
for x in range(1, 11):
-
print x
-
time.sleep(1)
-
if x == 3:
-
pass
-
if x == 2:
-
continue
-
if x == 6:
-
break
-
if x == 7:
-
exit()
-
print '#'*50
3、while
while的用途也是循環。它首先檢查在它後邊的循環條件,若條件表達式爲真,它就執行冒號後面的語句塊,然後再次測試循環條件,直至爲假。冒號後面的縮近語句塊爲循環體。
-
-
-
-
while expression:
-
statement(s)
-
-
while True:
-
print 'hello'
-
x = raw_input('please input something, q for quit:')
-
if x == 'q':
-
break
-
else:
-
print 'ending'
4、switch
其實Python並沒有提供switch結構,但我們可以通過字典和函數輕鬆的進行構造。例如:
-
-
-
-
-
-
-
-
from __future__ import division
-
-
-
def add(x, y):
-
return x + y
-
def sub(x, y):
-
return x - y
-
def mul(x, y):
-
return x * y
-
def div(x, y):
-
return x / y
-
-
operator = {"+": add, "-": sub, "*": mul, "/": div}
-
operator["+"](1, 2)
-
operator["%"](1, 2)
-
operator.get("+")(1, 2)
-
-
def cal(x, o, y):
-
print operator.get(o)(x, y)
-
cal(2, "+", 3)
-
五、函數
1、自定義函數
在Python中,使用def語句來創建函數:
-
-
-
def functionName(parameters):
-
bodyOfFunction
-
-
def add(a, b):
-
return a+b
-
-
a = 100
-
b = 200
-
sum = add(a, b)
-
-
-
-
-
def add(a = 1, b = 2):
-
return a+b
-
-
add()
-
add(2)
-
add(y = 1)
-
add(3, 4)
-
-
-
-
-
-
-
-
val = 100
-
def fun():
-
print val
-
print val
-
-
def fun():
-
a = 100
-
print a
-
print a
-
-
def fun():
-
global a = 100
-
print a
-
-
print a
-
fun()
-
print a
-
-
-
-
def fun(x):
-
print x
-
-
fun(10)
-
fun('hello')
-
fun(('x', 2, 3))
-
fun([1, 2, 3])
-
fun({1: 1, 2: 2})
-
-
-
def fun(x, y):
-
print "%s : %s" % (x,y)
-
fun('Zou', 'xiaoyi')
-
tu = ('Zou', 'xiaoyi')
-
fun(*tu)
-
-
-
def fun(name = "name", age = 0):
-
print "name: %s" % name
-
print "age: " % age
-
dic = {name: "xiaoyi", age: 25}
-
fun(**dic)
-
fun(age = 25, name = 'xiaoyi')
-
-
-
-
-
-
def fun(x, *args):
-
print x
-
print args
-
-
fun(10)
-
fun(10, 12, 24)
-
-
-
def fun(x, **args):
-
print x
-
print args
-
-
fun(10)
-
fun(x = 10, y = 12, z = 15)
-
-
-
def fun(x, *args, **kwargs):
-
print x
-
print args
-
print kwargs
-
fun(1, 2, 3, 4, y = 10, z = 12)
2、Lambda函數
Lambda函數用來定義一個單行的函數,其便利在於:
-
-
-
-
fun = lambda x,y : x*y
-
fun(2, 3)
-
-
def fun(x, y):
-
return x*y
-
-
-
-
def recursion(n):
-
if n > 0:
-
return n * recursion(n-1)
-
-
def mul(x, y):
-
return x * y
-
numList = range(1, 5)
-
reduce(mul, numList)
-
reduce(lambda x,y : x*y, numList)
-
-
-
numList = [1, 2, 6, 7]
-
filter(lambda x : x % 2 == 0, numList)
-
print [x for x in numList if x % 2 == 0]
-
map(lambda x : x * 2 + 10, numList)
-
print [x * 2 + 10 for x in numList]
3、Python內置函數
Python內置了很多函數,他們都是一個個的.py文件,在python的安裝目錄可以找到。弄清它有那些函數,對我們的高效編程非常有用。這樣就可以避免重複的勞動了。下面也只是列出一些常用的:
-
-
-
-
abs, max, min, len, divmod, pow, round, callable,
-
isinstance, cmp, range, xrange, type, id, int()
-
list(), tuple(), hex(), oct(), chr(), ord(), long()
-
-
callable
-
-
-
isinstance
-
numList = [1, 2]
-
if type(numList) == type([]):
-
print "It is a list"
-
if isinstance(numList, list):
-
print "It is a list"
-
-
for i in range(1, 10001)
-
for i in xrange(1, 10001)
-
-
-
str = 'hello world'
-
str.capitalize()
-
str.replace("hello", "good")
-
ip = "192.168.1.123"
-
ip.split('.')
-
help(str.split)
-
-
import string
-
str = 'hello world'
-
string.replace(str, "hello", "good")
-
-
-
len, max, min
-
-
def fun(x):
-
if x > 5:
-
return True
-
numList = [1, 2, 6, 7]
-
filter(fun, numList)
-
filter(lambda x : x % 2 == 0, numList)
-
-
name = ["me", "you"]
-
age = [25, 26]
-
tel = ["123", "234"]
-
zip(name, age, tel)
-
-
map(None, name, age, tel)
-
test = ["hello1", "hello2", "hello3"]
-
zip(name, age, tel, test)
-
map(None, name, age, tel, test)
-
a = [1, 3, 5]
-
b = [2, 4, 6]
-
def mul(x, y):
-
return x*y
-
map(mul, a, b)
-
-
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
六、包與模塊
1、模塊module
python中每一個.py腳本定義一個模塊,所以我們可以在一個.py腳本中定義一個實現某個功能的函數或者腳本,這樣其他的.py腳本就可以調用這個模塊了。調用的方式有三種,如下:
-
-
-
-
-
-
-
-
-
def add(x, y):
-
return x + y
-
def sub(x, y):
-
return x - y
-
def mul(x, y):
-
return x * y
-
def div(x, y):
-
return x / y
-
-
print "Your answer is: ", add(3, 5)
-
-
if __name__ == "__main__"
-
r = add(1, 3)
-
print r
-
-
-
import cal
-
-
-
-
-
-
result = cal.add(1, 2)
-
print result
-
-
import cal as c
-
result = c.add(1, 2)
-
-
from cal import add
-
result = add(1, 2)
2、包package
python 的每個.py文件執行某種功能,那有時候我們需要多個.py完成某個更大的功能,或者我們需要將同類功能的.py文件組織到一個地方,這樣就可以很方便我們的使用。模塊可以按目錄組織爲包,創建一個包的步驟:
# 1、建立一個名字爲包名字的文件夾
# 2、在該文件夾下創建一個__init__.py空文件
# 3、根據需要在該文件夾下存放.py腳本文件、已編譯拓展及子包
# 4、import pack.m1,pack.m2 pack.m3
-
-
-
-
-
-
-
mkdir calSet
-
cd calSet
-
touch __init_.py
-
cp cal.py .
-
-
-
import calSet.cal
-
result = calSet.cal.add(1, 2)
-
print result
七、正則表達式
正則表達式,(英語:RegularExpression,在代碼中常簡寫爲regex、regexp或RE),計算機科學的一個概念。正則表達式使用單個字符串來描述、匹配一系列符合某個句法規則的字符串。在很多文本編輯器裏,正則表達式通常被用來檢索、替換那些符合某個模式的文本。
Python提供了功能強大的正則表達式引擎re,我們可以利用這個模塊來利用正則表達式進行字符串操作。我們用import re來導入這個模塊。
正則表達式包含了很多規則,如果能靈活的使用,在匹配字符串方面是非常高效率的。更多的規則,我們需要查閱其他的資料。
1、元字符
很多,一些常用的元字符的使用方法如下:
-
-
-
-
import re
-
rule = r'abc'
-
re.findall(rule, "aaaaabcaaaaaabcaa")
-
-
-
rule = r"t[io]p"
-
re.findall(rule, "tip tep twp top")
-
-
-
rule = r"t[^io]p"
-
re.findall(rule, "tip tep twp top")
-
-
-
rule = r"^hello"
-
re.findall(rule, "hello tep twp hello")
-
re.findall(rule, "tep twp hello")
-
-
-
rule = r"hello$"
-
re.findall(rule, "hello tep twp hello")
-
re.findall(rule, "hello tep twp")
-
-
-
rule = r"x[0123456789]x"
-
rule = r"x[0-9]x"
-
re.findall(rule, "x1x x4x xxx")
-
rule = r"x[a-zA-Z]x"
-
-
-
rule = r"\^hello"
-
re.findall(rule, "hello twp ^hello")
-
-
-
-
-
-
-
-
-
-
-
-
-
-
rule = r"^020-\d\d\d\d\d\d\d\d$"
-
rule = r"^020-\d{8}$"
-
rule = r"^020-[0-9]{8}$"
-
re.findall(rule, "020-23546813")
-
-
-
rule = r"ab*"
-
re.findall(rule, "a")
-
re.findall(rule, "ab")
-
-
-
rule = r"ab+"
-
re.findall(rule, "a")
-
re.findall(rule, "ab")
-
re.findall(rule, "abb")
-
-
-
rule = r"^020-?\d{8}$"
-
re.findall(rule, "02023546813")
-
re.findall(rule, "020-23546813")
-
re.findall(rule, "020--23546813")
-
-
-
rule = r"ab+?"
-
re.findall(rule, "abbbbbbb")
-
-
-
rule = r"a{1,3}"
-
re.findall(rule, "a")
-
re.findall(rule, "aa")
-
re.findall(rule, "aaa")
-
re.findall(rule, "aaaa")
-
-
-
rule = r"\d{3,4}-?\d{8}"
-
re.findall(rule, "020-23546813")
-
-
-
p_tel = re.compile(rule)
-
p_tel.findall("020-23546813")
-
-
-
name_re = re.compile(r"xiaoyi", re.I)
-
name_re.findall("Xiaoyi")
-
name_re.findall("XiaoYi")
-
name_re.findall("xiAOyi")
2、常用函數
Re模塊作爲一個對象,它還支持很多的操作,例如:
-
-
-
obj = name_re.match('Xiaoyi, Zou')
-
-
obj = name_re.search('Zou, Xiaoyi')
-
-
if obj:
-
pass
-
-
name_re.findall("Xiaoyi")
-
-
-
name_re.finditer("Xiaoyi")
-
-
-
rs = r"z..x"
-
re.sub(rs, 'python', 'zoux ni ziox me')
-
re.subn(rs, 'python', 'zoux ni ziox me')
-
-
-
str = "123+345-32*78"
-
re.split(r'[\+\-\*]', str)
-
-
-
dir(re)
-
-
-
-
str =
-
-
-
-
-
-
re.findall(r'xiaoyi', str, re.M)
3、分組
分組有兩個作用,它用()來定義一個組,組內的規則只對組內有效。
另外,分組可以優先返回分組內匹配的字符串。
-
-
str =
-
-
-
-
-
r1 = r"hello name=.+ yes"
-
re.findall(r1, str)
-
r2 = r"hello name=(.+) yes"
-
re.findall(r2, str)
-
-
4、一個小實例-爬蟲
這個實例利用上面的正則和分組的優先返回特性來實現一個小爬蟲算法。它的功能是到一個給定的網址裏面將.jpg後綴的圖片全部下載下來。
-
-
-
-
-
-
import re
-
import urllib
-
-
-
def getHtml(url):
-
print 'Getting html source code...'
-
page = urllib.open(url)
-
html = page.read()
-
return html
-
-
-
-
def getImageAddrList(html):
-
print 'Getting all address of images...'
-
rule = r"src=\"(.+\.jpg)\" pic_ext"
-
imReg = re.compile(rule)
-
imList = re.findall(imReg, html)
-
return imList
-
-
def getImage(imList):
-
print 'Downloading...'
-
name = 1;
-
for imgurl in imList:
-
urllib.urlretrieve(imgurl, '%s.jpg' % name)
-
name += 1
-
print 'Got ', len(imList), ' images!'
-
-
-
htmlAddr = "http://tieba.baidu.com/p/2510089409"
-
html = getHtml(htmlAddr)
-
imList = getImageAddrList(html)
-
getImage(imList)
八、深拷貝與淺拷貝
Python中對數據的複製有兩個需要注意的差別:
淺拷貝:對引用對象的拷貝(只拷貝父對象),深拷貝:對對象資源的拷貝。具體的差別如下:
-
-
-
-
-
-
a = [1, 2, 3]
-
b = a
-
a.append(4)
-
-
import copy
-
a = [1, 2, ['a', 'b']]
-
c = copy.copy(a)
-
a.append('d')
-
-
-
-
a[2].append('d')
-
a[1] = 3
-
-
-
d = copy.deepcopy(a)
-
九、文件與目錄
1、文件讀寫
Python的文件操作和其他的語言沒有太大的差別。通過open或者file類來訪問。但python支持了很多的方法,以支持文件內容和list等類型的交互。具體如下:
-
-
-
-
-
-
-
fin = open('./test.txt')
-
fin.read()
-
fin.close()
-
-
-
fin = file('./test.txt')
-
fin.read()
-
fin.close()
-
-
-
fin = open('./test.txt', 'r+')
-
fin.write('hello')
-
fin.close()
-
-
-
-
-
for i in open('test.txt'):
-
print i
-
-
str = fin.readline()
-
list = fin.readlines()
-
fin.next()
-
-
-
fin.writelines(list)
-
-
-
fin.seek(0, 0)
-
fin.seek(0, 1)
-
fin.seek(-1, 2)
-
-
-
fin.flush()
2、OS模塊
os模塊提供了很多對系統的操作。例如對目錄的操作等。我們需要用import os來插入這個模塊以便使用。
-
-
-
-
import os
-
-
os.mkdir('xiaoyi')
-
os.makedirs('a/b/c', mode = 666)
-
os.listdir()
-
os.chdir()
-
os.getcwd()
-
os.rmdir()
3、目錄遍歷
目錄遍歷的實現可以做很多普遍的功能,例如殺毒軟件,垃圾清除軟件,文件搜索軟件等等。因爲他們都涉及到了掃描某目錄下所有的包括子目錄下的文件。所以需要對目錄進行遍歷。在這裏我們可以使用兩種方法對目錄進行遍歷:
1)遞歸
-
-
-
import os
-
-
def dirList(path):
-
fileList = os.listdir(path)
-
allFile = []
-
for fileName in fileList:
-
-
filePath = os.path.join(path, fileName)
-
if os.path.isdir(filePath):
-
dirList(filePath)
-
allFile.append(filePath)
-
return allFile
2)os.walk函數
-
-
gen = os.walk('/')
-
for path, dir, filelist in os.walk('/'):
-
for filename in filelist:
-
os.path.join(path, filename)
十、異常處理
異常意味着錯誤,未經處理的異常會中止程序運行。而異常拋出機制,爲程序開發人員提供一種在運行時發現錯誤,並進行恢復處理,然後繼續執行的能力。
-
-
-
-
-
-
-
-
try:
-
fin = open("abc.txt")
-
print hello
-
-
except IOError, msg:
-
print "On such file!"
-
-
except NameError, msg:
-
print msg
-
-
finally:
-
print 'ok'
-
-
-
if filename == "hello":
-
raise TypeError("Nothing!!")