本學習筆記針對有其他語言基礎的情況下記錄的, 主要記錄一些與其他語言不一樣的地方, 使用于快速學習.
常用指令
- print 打印
- id 顯示內(nèi)存地址
- help 幫助
- div
- type
整數(shù)溢出
利用模塊解決除法和編碼格式(支持中文)的方法
引入模塊
- import math
- from xxxx1 import xxxx2 // xxxx2是xxxx1大模塊中的小模塊
數(shù)和四則運算
divmod(5,2) 5 % 2 模
round(2.222) 四舍五入
字符串
> "Py" + "thon"
> a = 1234
print "hehe" + `a` // 引號是1旁邊的那個`
print "hehe" + str(a)
print "hehe" + repr(a) // repr() is a function instead of ``
> name = raw_input("input your name:")
> a = 10; b = 20
> print a,b
> c = "C:\news"
> print c
> print r"C:\news"
> ord('b') // 98
> chr(98) // 'b'
> c = "abc"
> c * 3 // 'abcabcabc'
> "+" * 20 // out put 20 '+'
raw_input(...) </br>
raw_input([prompt]) -> string </br>
Read a string from standard input. The trailing newline is stripped.</br>
If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.</br>
On Unix, GNU readline is used if enabled. The prompt string, if given,
is printed without a trailing newline before reading. </br>
基本操作
- len()
- in // return False or Ture
- max()
- min()
- cmp(str1,str2) // same is 0, less is -1 , bigger is 1
格式化輸出
> a = "grayland"
> "my name is %s" % a
> "my name is {}".format(a)
> "my name is {name}, age is {age}".format(name=a, age=27) // 推薦
> "my name is %(name)s"%{"name":a}
常用方法
> a = "my name is grayland"
> a.split(" ") // return a list, 反過來是 join
> a.strip() // 去掉左右空格
> a.lstrip(), a.rstrip()
> a.upper()
> a.lower()
> a.capitalize() // First character uppper
> a.isupper()
> a.islower()
> a.istitle()
Python 避免中文是亂碼
- # -- coding: utf-8 -- // -*- 沒有用
- # coding:utf-8
- unicode_str = unicode('中文', encoding='utf-8') // 遇到字符(節(jié))串,立刻轉(zhuǎn)化為 unicode,不要用 str()蜻懦,直接使用 unicode()
- import codecs</br>
codecs.open('filename', encoding='utf8') </br>遇到字符(節(jié))串得封,立刻轉(zhuǎn)化為 unicode纵潦,不要用 str()店归,直接使用 unicode()
索引和切片
> a = "python"
a[0]
// p
a[1]
// y
a.index("p")
// 0
a[1:3]
// 'yt'
a[1:99999]
a[1:] // index 1 to end
a[:] // get all
a[:3] // first to 3
列表 List
相當于 NSArray. 列表可以無限大.
- insert(index, obj)
- append 添加元素 listA.append(obj), obj必須是 iterable 可迭代的.
- extend 擴展 listA.extend(listB)
- remove(obj) only remove the first object, if obj not exist cause an error.
- pop(index) if index not exist , then remove the last.
- reverse()
- sort()
- same as extend
list str 轉(zhuǎn)化:
- split
- join
判斷對象是否可迭代:</br>
判斷其屬性有 'iter'屬性</br>
hasattr(obj, 'iter') // Trure or False
元組 tuple
元組是用圓括號括起來的仇哆,其中的元素之間用逗號隔開靶衍。</br>
元組中的元素類型是任意的 Python 數(shù)據(jù)灾炭。</br>
元組不能修改, list 和 str 的融合產(chǎn)物
- tuple 操作比 list 快.
- 不能修改數(shù)據(jù), 安全
- tuple 可以用作 key,list 不可以
- tuple 可以用在字符串格式化總
a = 111,222,'ccc' // then a is tuple
元組可以用于格式化:
"my name is %s, age is %d"%("grayland", 27)
字段 dict
創(chuàng)建字典:
> dictA = {}
> dictA = {'key'='value'}
> dictA['key'] = 'value'
> dictA = dict((['key1':'value1'], ['key2':'value2'])) // 利用元組構(gòu)造
> dictA = dict(key='value',key2='value')
> dictA = {}.formkeys(('key1','key2'), 'value')
訪問字典:
> D = {'name':'grayland, 'age':27}
> D['gender'] // Error
> D.get('gender') // get nothing
其他方法:
- len(dictX) // get the num of key-value.
- del d[key] // delete the key-value pair in the dict 'd'.
- key in d
- copy // a = b.copy(), import copy, can use copy.deepcopy(obj)
- clear()->None // Remove all items
- get(key)
- get(key, default) // If key no exist, return default.
- setdefault() // as get(key,default), but if key not exist then add to de dict
- items() // return list[(tuple), (tuple), ...]
- pop(key)
- popitems() // Random to pop 1 key-value pair
- update(dictX) // Cover with dictX
- has_key(key)
字符串格式化輸出:
"my name is %(key)s" % {'key':'value'} // >> 'my name is value'
集合 Set
無序,不重復.</br>
tuple 類似 list 和 str 的集合. </br>
set 類似 list 和 dict 的集合.</br>
> s1 = set('abcdefff')
set(['a', 'c', 'b', 'e', 'd', 'f']) // It haven't repeat element
s1 = {'a','b','c','d','e','f','f','f'} same as set(...)
其他:
add(obj)
pop()
remove(obj)
discard(obj) // same as remove(obj), but if not exist do nothing.
clear()
issubset(setB)
|
&
diffenece(setB) // 取反
語句
print obj, // 用在循環(huán)中, 不換行. 否則換行
import
> import math
> from math import pow
> from math import pow as pingfang
> from math import pow, e, pi
> from math import *
賦值語句
> x,y,z = 1,2,3
> x = 1,2,3
> x,y = y,x // 相當于 a=x;x=y;y=a; 實現(xiàn)對調(diào)
> x = y = 123 // 鏈式賦值, x = 123, y = 123 , 指向同一個地址.
>
條件語句
// If/else/elif
// 必須通過縮進方式來表示語句塊的開始和結(jié)束.
// 縮進使用四個空格
if xxx in xxxx:
...
elif:
...
else:
...
while
// while ...
while True:
if a:
break
//while...else
while ...:
...
else:
...
// for...else
for ... in ...:
...
else:
...
三元操作符
a = y if x else z // 如果 x is True return y else return z.
循環(huán)
> for i in "hello":
> for i in listA:
> for i in range(start, stop, step)
> for key in dictA:
> for k,v in dictA.items():
> for k,v in dictA.iteritems():
并行迭代
> a = [1,2,3,4,5]
> b = [9,8,7,6,5]
> // 求 ab 每項的和
> for i in range(len(a)):
> c.append(a[i]+b[i])
> // c = [10,10,10,10,10]
>
> for x,y in zip(a,b):
> c.append(x+y)
> // c = [10,10,10,10,10]
>
enumerate(listA) -> (index, listA[index])
enumerate(listA, start=10) -> (index+10, listA[index])
list 解析
for i in range(1,4):
a.append(i**2)
> [1,4,9]
list 解析:
a = [x**2 for x in range(1,4)]
> a = [1,4,9]
打開文件
> f = open("xxx.txt")
> for line in f:
> print line,
// f 類型是 file
// 此時 f 已經(jīng)到了文件的末尾, 再遍歷將不會輸出東西.
// close() 關閉并保存
with ... as ...: // 可以實現(xiàn)保存
文件狀態(tài)
import os
os 模塊中有 文件狀態(tài)的方法 stat(path)
import time // 時間相關模塊
read/readline/readlines
read:
read([size]) -> read at most size bytes, returned as a string.
If the size argument is negative or omitted, read until EOF is reached. Notice that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given.
readline:
readline([size]) -> next line from the file, as a string.
Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then). Return an empty string at EOF.
readlines:
readlines([size]) -> list of strings, each a line from the file.
Call readline() repeatedly and return a list of the lines so read.
The optional size argument, if given, is an approximate bound on the total number of bytes in the lines returned.
- seek(offset, whence) // whence default = 0, </br>0 - offset from begin offset must be positive +</br>1 - offset from current, offset should be positive/nagative +/-</br> 2 - offset from the end, offset must be nagative. -
- tell() // get current position
迭代
逐個訪問
> lst = ['g', 'r', 'a', 'y', 'l', 'a', 'n', 'd']
> for s in lst:
>
> lst_iter = iter(lst)
> lst_iter.next()
> lst_iter.next()
> lst_iter.next()
> ...
>
>
文件迭代器
> f = open(...)
> f.readline()
> f.next()
> is same.
>
> listA = list(open(...)) // 可以獲得文件的內(nèi)容
> tupleA = tuple(open(...))
>
> "stringAppend".join(open(...)) // file.readline->append(..>) then join
> a,b,c,d,e = open(...) // a,b,c,d,e 分別賦值 file.readline()
>
自省
- help() 進入 help 模式
- help(...)
- dir(...)
- __doc__
- __builtins__
- callable() 測試函數(shù)可調(diào)用性
- isinstance('strxxxxx', str) -> True
- issubclass(classB, classA) -> BOOL
函數(shù)
f(x) = ax + b
...
變量本質(zhì)上是一個占位符
定義
def func(inputA, inputB,...):
def func(X=default,Y=default):
def func(a,arg):* // *arg表示多個可變參數(shù) (tuple 類型傳遞)
變量無類型,對象有類型
Python 中為對象編寫接口,而不是為數(shù)據(jù)類型
命名
- 文件名:全小寫,可以使用下劃線
- 函數(shù)名:小寫,可以用下劃線風格增加可讀性 或 類似myFunction這樣的駝峰命名法
- 變量:全小寫
文檔
#: 注釋
""" ... """: 三個引號包圍表示文檔, 可以用 __doc__ 查看
傳值方式
> def funA(a,b):
> funA(1,2)
> input = (1,2)
> funA(input) // 元組參數(shù)
>
> funB(**dict) // 字典參數(shù)
> func(*args) // 可變參數(shù)
特殊函數(shù)
- filter(func, seq) // func(x)->bool
- map(func, seq) // excute func(x) in seq
- reduce(func, seq) // func(func(func(0,1),2),3),...
- lambda // lambda input:output
- yield
lambda:
> nums = range(10)
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
所有數(shù)+3
// Normal:
> result = [i+3 for i in nums]
// lambda:
> lam = lambda x:x+3
> for i in numbers:
> result.append(lam(i))
// map:
> def add(x):
> ...
> map(add,nums)
// filter:
// 過濾大于5的數(shù)
> [x for x in nums if x>5] // Mathod1
> filter(lambda x:x>5, nums) // Mathod2
類 class
對象的相關定義:
- 對象
- 狀態(tài)
- 行為
- 標識
簡化后就是: 屬性和方法
定義
舊類
深
> class Person:
> pass
> ...
> oldClass = Person()
> oldClass.__class__
> <class __main__.Person at 0x10a644ef0>
> type(Person)
> <type 'classobj'>
新類
廣
> class NewPerson(object):
> pass
> ...
> newClass = NewPerson()
> type(newClass)
> <class '__main__.NewPerson'>
> type(NewPerson)
> <class '__main__.NewPerson'>
>
> __metaclass__ = type // 寫在這句之下的都是新類,即便沒有(object)
>
(object) 表示繼承自 object 類. Python3 中全部繼承自 object 類.
初始化
> def __init__(self, *args) // self 是必須的
類屬性和實例屬性
可以動態(tài)修改和增加
> Person.propertyA = 'new value'
> obj1 = Person()
> obj1.newProperty = 'new value'
命名空間
- 內(nèi)置命名空間(Built-in Namespaces):Python 運行起來颅眶,它們就存在了蜈出。內(nèi)置函數(shù)的命名空間都屬于內(nèi) 置命名空間,所以涛酗,我們可以在任何程序中直接運行它們铡原,比如前面的 id(),不需要做什么操作,拿過來就直 接使用了商叹。
- 全局命名空間(Module:Global Namespaces):每個模塊創(chuàng)建它自己所擁有的全局命名空間燕刻,不同模塊的全 局命名空間彼此獨立,不同模塊中相同名稱的命名空間剖笙,也會因為模塊的不同而不相互干擾卵洗。
- 本地命名空間(Function&Class: Local Namespaces):模塊中有函數(shù)或者類,每個函數(shù)或者類所定義的命 名空間就是本地命名空間弥咪。如果函數(shù)返回了結(jié)果或者拋出異常过蹂,則本地命名空間也結(jié)束了。
查看命名空間:
print locals()
print golbals()
多重繼承順序
廣度優(yōu)先
> def class A1(B1, B2):
> def class A2(B1, B2):
> def class C1(A1, A2):
>
> C1.func()
> C1->A1->A2->B1->B2 // 廣度優(yōu)先 新類
> C1->A1->B1->B2->A2->B1->B2 // 深度優(yōu)先 舊類
super 函數(shù)
super(Class, self).init()
綁定方法
def func() 就是綁定方法
非綁定方法
父類的方法都是非綁定方法
調(diào)用非綁定方法
super(BaseClass, self).function()
靜態(tài)方法和類方法
- @staticmethod
- @classmethod
靜態(tài)方法參數(shù)沒有 self.
類方法參數(shù)沒有 self. 但是有 cls.
封裝和私有化
私有化:
方法數(shù)據(jù)名字前面加雙下劃線.
在方法前加 @property , obj.fun()-> obj.fun
特殊方法
__dict__:
動態(tài)添加修改刪除屬性的保存字典, 存儲對象成員.
__slots__:
鎖定類型, __dict__將不存在, 所有的屬性都是類屬性, 實例訪問是 readonly, 不能進行修改, 若要修改,只能通過類調(diào)用修改.
__setattr__(self,name,value):
obj.property = xxxx, 賦值時候調(diào)用 __setattr__, 可以重寫其攔截.
__getattr__(self,name) old:
__getattribute__(self,name):
obj.property , 獲取值時調(diào)用.
newProperty = propetty(getFunc,setFunc) # 第一個是 getter,第二個是 setter.順序不能換
obj.newProperty = xxx ->obj.setFunc
迭代器
重寫 __iter__ , next() -> raise StopIteration()
生成器
簡單的生成器
把含有 yield 的語句函數(shù)稱作生成器. 生成器是一種用普通函數(shù)語法定義的迭代器. 生成器也是迭代器, 使用 yield 語句,普通的函數(shù)就成了生成器,且具備迭代器功能特性.
> a = (x*x for x in range(4)) # 迭代的, 遍歷一遍后再輸出就沒有
> for i in a:
> print i,
> a = [x*x for x in range(4)] # 生成全部, 遍歷輸出一直有值
>
> def g():
> yiled 0
> yiled 1
> yiled 2
>
> a = g()
> a.next()
> ...
>
>
生成器解析式是有很多用途的聚至,在不少地方替代列表酷勺,是一個不錯的選擇。特別是針對大量值的時候扳躬,如上節(jié)所
說的脆诉,列表占內(nèi)存較多,迭代器(生成器是迭代器)的優(yōu)勢就在于少占內(nèi)存坦报,因此無需將生成器(或者說是迭代
器)實例化為一個列表库说,直接對其進行操作,方顯示出其迭代的優(yōu)勢片择。比如:
> sum(i*i for i in range(10)) # 可以少寫一個 ()
yiled
yiled 和 retur 的區(qū)別:
一般函數(shù)遇到 return 則返回并停止.</br>
遇到 yield 則掛起, 再遇到則從掛起位置繼續(xù)運行,直到結(jié)束拋出異常 StopIteration()
生成器方法
python2.5以后, 生成器可以在運行后給其提供新的值.
> def r(n):
> while True:
> n = (yield n)
>
> a = r(n)
> a.send('xxx') # Error, 要先啟動(next())才能 send.
> a.next() # 4
> a.next() # 4
> a.send('xxx') # 'xxx'
> a.next() # 空 None
>
調(diào)用一次 send(None)就是觸發(fā)一次 參數(shù)是 None 的 next. </br>
調(diào)用一次 next()就是觸發(fā)一次 send(n),但 send(n)之后的 yield n -> None
- throw(type, value=None, traceback=None):用于在生成器內(nèi)部(生成器的當前掛起處潜的,或未啟動時在定 義處)拋出一個異常(在 yield 表達式中)。
- close():調(diào)用時不用參數(shù)字管,用于關閉生成器啰挪。
錯誤和異常
錯誤
語法錯誤和邏輯錯誤, 遇到錯誤, 拋出異常.
異常
當 Python 拋出異常的時候信不,首先有“跟蹤記錄(Traceback)”,還可以給它取一個更優(yōu)雅的名字“回溯”亡呵。后 面顯示異常的詳細信息抽活。異常所在位置(文件、行锰什、在某個模塊)下硕。
最后一行是錯誤類型以及導致異常的原因。
異常 | 描述 |
---|---|
NameError | 嘗試訪問一個沒有申明的變量 |
ZeroDivisionError | 除數(shù)為 0 |
SyntaxError | 語法錯誤 |
IndexError | 索引超出序列范圍 |
KeyError | 請求一個不存在的字典關鍵字 |
IOError | 輸入輸出錯誤(比如你要讀的文件不存在) |
AttributeError | 嘗試訪問未知的對象屬性 |
處理異常
try...except...(else...)(finally...)
try...except...except... 處理多個異常
try...except (Error1,Error2):...
try...except (Error1,Error2), e: ...
try...except Exception,e
Python3.x:</br>
try...except(Error1,Error2) as e: ...
except 后面也可以沒有任何異常類型汁胆,即無異常參數(shù)梭姓。如果這樣,不論 try 部分發(fā)生什么異常嫩码,都會執(zhí)行 excep t誉尖。
raise 將異常信息拋出
> try:
> pass
> except NameError:
> pass
>
> ...
eval(...)
assert
assert 1 # Fine
assert 0 # Throw Error
- 防御性的編程
- 運行時對程序邏輯的檢測
- 合約性檢查(比如前置條件,后置條件)
- 程序中的常量
- 檢查文檔
模塊
模塊是程序 .py 文件.
自定義模塊還需要 python 能找到你的文件.
> import sys
> sys.path.append(yourPath)
> impot YourPythonModule
> YourPythonModule.protery
> YourPythonModule.func()
> ...
之后會增加 YourPythonModule.pyc 文件
如果是作為程序執(zhí)行
__name__ == "__main__"
如果作為模塊引入 __name__ == "YourPythonModule"
在一般情況下铸题,如果僅僅是用作模塊引入铡恕,可以不寫 if __name__ == "__main__"
。
PYTHONPATH 環(huán)境變量
__init__.py 方法
是一個空文件丢间,將它放在某個目錄中探熔,就可以將該目錄中的其它 .py 文件作為模塊被引用。
標準庫
引用方式
import xxxxx
> import pprint
> pprint.pprint(xxxx)
> from pprint import pprint
> pprint(xxxx)
> import pprint as p
> p.pprint(xxxx)
__file__ 查看庫的源文件
sys
argv
import sys
sys.argv #入口參數(shù) 第一個一般是文件名
print "The file name: ", sys.argv[0]
print "The number of argument", len(sys.argv)
print "The argument is: ", str(sys.argv)
exit
- sys.exit() # 退出當前程序 返回 SystemExit
- sys.exit(0) # 正常退出
- sys.exit('some infomation')
- sys_exit() # 退出當前程序
path
查找模塊的搜索目錄
stdin,stdout,stderr
變量都是類文件流對象.
stdin-> raw_input() -> python3.x -> input()
print() -> stdout.write(obj+'\n')
輸出到文件中:
> f = open(path,'w')
> sys.stdout = f
> ...
> print '...' # 寫到文件中
> ...
> f.close()
OS
重命名,刪除文件
- rename(old,new)
- remove(path) #刪除文件, 不能刪除目錄
- listdir()
- getcwd() #當前工作目錄
- chdir(path) #改變當前工作目錄 -> cd
- pardir() #獲得父級目錄 -> ..
- makedir
- makedirs #中間的目錄也會被建立起來
- removedirs #刪除空目錄
- shutil.rmtree(dir)
文件和目錄屬性
- stat(path)
- chmod()
- system(shellCommand) #當前線程執(zhí)行
- exec() or execvp() #新的進程中執(zhí)行
打開瀏覽器
> import os
> os.system(browserPath + " www.baidu.com")
> import webbrowser as w
> w.open(url)
heapq
['about', 'all', 'builtins', 'doc', 'file', 'name', 'package', '_heapify_max', '_heappushpop_max', '_nlargest', '_nsmallest', '_siftdown', '_siftdown_max', '_siftup', '_siftup_max', 'chain', 'cmp_lt', 'count', 'heapify', 'heappop', 'heappush', 'heappushpop', 'heapreplace', 'imap', 'islice', 'itemgetter', 'izip', 'merge', 'nlargest', 'nsmallest', 'tee']
- heappush(heap, item)
- heappop() # pop minimun item
- heapify() # list to heap
- heapreplace(heap, item) # pop then push
deque
['class', 'copy', 'delattr', 'delitem', 'doc', 'eq', 'format', 'ge', 'getattribute', 'getitem', 'gt', 'hash', 'iadd', 'init', 'iter', 'le', 'len', 'lt', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'reversed', 'setattr', 'setitem', 'sizeof', 'str', 'subclasshook', 'append', 'appendleft', 'clear', 'count', 'extend', 'extendleft', 'maxlen', 'pop', 'popleft', 'remove', 'reverse', 'rotate']
- deque(list)->deque object
- append(item) #right
- appendleft(item) #left
- pop() #right
- popleft() #left
- extend() #left
- extendleft() #right
- rotate(offset) #正數(shù), 指針左移. 負數(shù),指針右移
calendar
import calendar
['Calendar', 'EPOCH', 'FRIDAY', 'February', 'HTMLCalendar', 'IllegalMonthError', 'IllegalWeekdayError', 'January', 'LocaleHTMLCalendar', 'LocaleTextCalendar', 'MONDAY', 'SATURDAY', 'SUNDAY', 'THURSDAY', 'TUESDAY', 'TextCalendar', 'TimeEncoding', 'WEDNESDAY', '_EPOCH_ORD', 'all', 'builtins', 'doc', 'file', 'name', 'package', '_colwidth', '_locale', '_localized_day', '_localized_month', '_spacing', 'c', 'calendar', 'datetime', 'day_abbr', 'day_name', 'error', 'firstweekday', 'format', 'formatstring', 'isleap', 'leapdays', 'main', 'mdays', 'month', 'month_abbr', 'month_name', 'monthcalendar', 'monthrange', 'prcal', 'prmonth', 'prweek', 'setfirstweekday', 'sys', 'timegm', 'week', 'weekday', 'weekheader']
- calendar(year) # 打印日歷
- isleap # 是否是閏年
- leapdays(y1,y2) # 兩年之間的閏年總數(shù)
- month(year,month) # 打印月份
- monthcalendar(year,month) #返回當月天數(shù)的嵌套數(shù)組
- monthrange(year,month) #->(a,b) 該月第一天是星期幾, 一共有幾天
- wekkday(year,month,day) #-> 星期幾
time
import time
- time() # -> now
- localtime() # -> year,month,monthday,hour,min,sec,wday,yday,isdst(夏令時)
- gmtime() # 格林威治時間 GMT
- asctime() # friendly ui like -> Mon Jan 12 00:00:00 2017
- mktime(timelist) -> number
- strftime(fmt) # strftime('%Y-%m-%d %H:%M:%S')->'2017-06-09 16:09:45'
- strptime(input, fmt) # -> numbers strftime 的反轉(zhuǎn)換
datetime
- date: 日期類千劈,常用的屬性有 year/month/day
- date.today()
- date.ctime()
- date.timetuple()
- date.toordinal()
- time: 時間類祭刚,常用的有 hour/minute/second/microsecond
- datetime: 期時間類
- timedelta: 時間間隔類
- tzinfo: 時區(qū)類
urllib
網(wǎng)絡模塊
['ContentTooShortError', 'FancyURLopener', 'MAXFTPCACHE', 'URLopener', 'all', 'builtins', 'doc', 'file', 'name', 'package', 'version', '_asciire', '_ftperrors', '_get_proxies', '_get_proxy_settings', '_have_ssl', '_hexdig', '_hextochr', '_hostprog', '_is_unicode', '_localhost', '_noheaders', '_nportprog', '_passwdprog', '_portprog', '_queryprog', '_safe_map', '_safe_quoters', '_tagprog', '_thishost', '_typeprog', '_urlopener', '_userprog', '_valueprog', 'addbase', 'addclosehook', 'addinfo', 'addinfourl', 'always_safe', 'base64', 'basejoin', 'c', 'ftpcache', 'ftperrors', 'ftpwrapper', 'getproxies', 'getproxies_environment', 'getproxies_macosx_sysconf', 'i', 'localhost', 'noheaders', 'os', 'pathname2url', 'proxy_bypass', 'proxy_bypass_environment', 'proxy_bypass_macosx_sysconf', 'quote', 'quote_plus', 're', 'reporthook', 'socket', 'splitattr', 'splithost', 'splitnport', 'splitpasswd', 'splitport', 'splitquery', 'splittag', 'splittype', 'splituser', 'splitvalue', 'ssl', 'string', 'sys', 'test1', 'thishost', 'time', 'toBytes', 'unquote', 'unquote_plus', 'unwrap', 'url2pathname', 'urlcleanup', 'urlencode', 'urlopen', 'urlretrieve']
> import urllib as T
> data = T.urlopen("http:....")
> print data.read()
>
> #data Is iterable
> data.info()
> data.getcode() # return status code - 200
> data.geturl()
>
- urlopen(url,PostData,proxies) -> 'class to add info() and geturl() methods to an open file.'
- urlretrieve(url,localpathname, 回調(diào)=None,請求數(shù)據(jù)=None) # 回調(diào) args->a,b,c progress = 100.0 * a * b / c
編解碼
- quite(string[,safe]): 對字符串進行編碼。參數(shù) safe 指定了不需要編碼的字符
- urllib.unquote(string) :對字符串進行解碼
- quote_plus(string [ , safe ] ) :與 urllib.quote 類似墙牌,但這個方法用'+'來替換空格 ' ' 涡驮,而 quote 用'%2 0'來代替空格
- unquote_plus(string ) :對字符串進行解碼;
- urllib.urlencode(query[, doseq]):將 dict 或者包含兩個元素的元組列表轉(zhuǎn)換成 url 參數(shù)。例如{'name': 'laoqi', 'age': 40}將被轉(zhuǎn)換為"name=laoqi&age=40"
- pathname2url(path):將本地路徑轉(zhuǎn)換成 url 路徑
urllib2
urllib2 是另外一個模塊喜滨,它跟 urllib 有相似的地方——都是對 url 相關的操作捉捅,也有不同的地方。
['AbstractBasicAuthHandler', 'AbstractDigestAuthHandler', 'AbstractHTTPHandler', 'BaseHandler', 'CacheFTPHandler', 'FTPHandler', 'FileHandler', 'HTTPBasicAuthHandler', 'HTTPCookieProcessor', 'HTTPDefaultErrorHandler', 'HTTPDigestAuthHandler', 'HTTPError', 'HTTPErrorProcessor', 'HTTPHandler', 'HTTPPasswordMgr', 'HTTPPasswordMgrWithDefaultRealm', 'HTTPRedirectHandler', 'HTTPSHandler', 'OpenerDirector', 'ProxyBasicAuthHandler', 'ProxyDigestAuthHandler', 'ProxyHandler', 'Request', 'StringIO', 'URLError', 'UnknownHandler', 'builtins', 'doc', 'file', 'name', 'package', 'version', '_cut_port_re', '_have_ssl', '_opener', '_parse_proxy', '_safe_gethostbyname', 'addinfourl', 'base64', 'bisect', 'build_opener', 'ftpwrapper', 'getproxies', 'hashlib', 'httplib', 'install_opener', 'localhost', 'mimetools', 'os', 'parse_http_list', 'parse_keqv_list', 'posixpath', 'proxy_bypass', 'quote', 'random', 'randombytes', 're', 'request_host', 'socket', 'splitattr', 'splithost', 'splitpasswd', 'splitport', 'splittag', 'splittype', 'splituser', 'splitvalue', 'ssl', 'sys', 'time', 'toBytes', 'unquote', 'unwrap', 'url2pathname', 'urlopen', 'urlparse', 'warnings']
Request
// 請求一個頁面數(shù)據(jù)
> req = urllib2.Request("...") #建立連接
> response = urllib2.urlopen(req)
> page = response.read()
> print page
// 一個 POST 例子
> url = '...'
>
> userAgent = 'Mozilla/5.0 (iPad; CPU OS 9_1 like Mac OS X) AppleWebKit/601.1 (KHTML, like Gecko) CriOS/58.0.3029.110 Mobile/13B143 Safari/601.1.46'
> headers = {'User-Agent':userAgent}
> params = {key:value,...}
>
> data = urllib.urlencode(params) #編碼
> req = urllib2.Request(url,data,headers) #請求
> response = urllib2.urlopen(req) #開始請求并接受返回信息
> pagedata = response.read() #讀取反饋內(nèi)容
>
// 除此之外還可以設置:
// HTTP Proxy
// Timeout
// redirect
// cookit
XML
Summary from w3school:
- XML 指可擴展標記語言(EXtensible Markup Language)
- XML 是一種標記語言虽风,很類似 HTML
- XML 的設計宗 是傳輸數(shù)據(jù)棒口,而非顯示數(shù)據(jù)
- XML 標簽沒有被預定義。您需要自行定義標簽辜膝。
- XML 被設計為具有自我描述性无牵。
- XML 是 W3C 的推薦標準
import xml
xml.__all__ </br>
['dom', 'parsers', 'sax', 'etree']:
- xml.dom.* 模塊:</br>Document Object Model。適合用于處理 DOM API厂抖。它能夠?qū)?xml 數(shù)據(jù)在內(nèi)存中解析 成一個樹茎毁,然后通過對樹的操作來操作 xml。但是,這種方式由于將 xml 數(shù)據(jù)映射到內(nèi)存中的樹七蜘,導致比較 慢谭溉,且消耗更多內(nèi)存。
- xml.sax.* 模塊:</br>simple API for XML橡卤。由于 SAX 以流式讀取 xml 文件扮念,從而速度較快,切少占用內(nèi) 存碧库,但是操作上稍復雜柜与,需要用戶實現(xiàn)回調(diào)函數(shù)。
- xml.parser.expat:</br>是一個直接的谈为,低級一點的基于 C 的 expat 的語法分析器喂窟。 expat 接口基于事件反 饋酥泞,有點像 SAX 但又不太像,因為它的接口并不是完全規(guī)范于 expat 庫的霸旗。
- xml.etree.ElementTree (以下簡稱 ET):</br>元素樹签舞。它提供了輕量級的 Python 式的 API秕脓,相對于 DOM,E T 快了很多 儒搭,而且有很多令人愉悅的 API 可以使用;相對于 SAX吠架,ET 也有 ET.iterparse 提供了 “在空 中” 的處理方式,沒有必要加載整個文檔到內(nèi)存搂鲫,節(jié)省內(nèi)存傍药。ET 的性能的平均值和 SAX 差不多,但是 API 的效率更高一點而且使用起來很方便魂仍。
所以, 推薦使用 ElementTree:
// Python2.x
> try:
> import xml.etree.cElementTree as et
> except ImportError:
> import xml.etree.ElementTree as et
// Python3.x
> import xml.etree.ElementTree as et
2.x的 ElementTree 模塊已經(jīng)跟教程不一樣了..之后再學3.x 的教程.
JSON
- key-value pairs: Named object/record/struct/dictionary/hash table/keyed list/associative array in difference language.
- order list of array: In mostly language , it construed array.
Function:
- encoding: python object to json string
- decoding: json string to python object
Object -> JSON : json.dumps(obj)
JSON -> Object : json.loads(...)
but after ljson.loads(...), result have a char type, here is the char type list:
Python==> | JSON |
---|---|
dict | object |
list, tuple | array |
str,unicode | string |
int ,long ,float | number |
True | true |
False | false |
None | null |
JSON==> | Python |
---|---|
object | dict |
array | list |
string | unicode |
number(int) | int,long |
number(real) | float |
true | True |
false | False |
null | None |
Third Part Lib
Install mathod:
- With code file: Python setup.py install , 這種是在本地的
- pip: 官方推薦 pip , 第三方庫管理工具.https://pypi.python.org/pypi
For example, use requests lib:
pip install requests
> import requests
> #get
> r = requests.get(url)
> r.cookies
> r.headers
> r.encoding # UTF-8
> r.status_code # 200
> print r.text # ...
> r.content
> #post
> params = {key:value,...}
> r = requests.post(url, params)
> #http header
> r.headers['content-type'] # 不用區(qū)分大小寫
>
數(shù)據(jù)讀寫
pickle/cpickle
pickle/cpickle 后者更快.
> import pickle
> f = open(path, 'wb')
> pickle.dump(listA/dictA, f, protocol=0) # protocol = 1 or True then use binary zip to achrive
> f.close()
shelve
pickle 的升級版, 處理復雜數(shù)據(jù).
#write
> import shelve
> s = shelve.open(path, writeback=True) # writeback=True 才可以修改已有的值
> s['name'] = 'grayland'
> ...
> s['data'] = {...}
> ...
> s.close()
#read
> s = shelve.open(path)
> name = s['name']
> ...
> data = s['data']
> ...
> for k in s:
> pass
> ...
>
>
mysql
到目前為止拐辽,地球上有三種類型的數(shù)據(jù):
- 關系型數(shù)據(jù)庫:MySQL、Microsoft Access擦酌、SQL Server俱诸、Oracle、...
- 非關系型數(shù)據(jù)庫:MongoDB睁搭、BigTable(Google)、...
- 鍵值數(shù)據(jù)庫:Apache Cassandra(Facebook)园骆、LevelDB(Google) ...
在本教程中,我們主要介紹常用的開源的數(shù)據(jù)庫锌唾,其中 MySQL 是典型代表。
安裝
sudo apt-get install mysql-server
配置
service mysqld start
創(chuàng)建好后的 root 沒有密碼:
$mysql -u rootfirehare
進入 mysql 之后捶牢,會看到>符號開頭巍耗,這就是 mysql 的命令操作界面了渐排。
設置密碼:
mysql> GRANT ALL PRIVILEGES ON *.* TO root@localhost IDENTIFIED BY "123456";
運行
$ mysql -u root -p Enter password:
mysql> show databases;
+--------------------+ | Database | +--------------------+ | information_schema |
|
| |
| carstore | cutvideo | itdiffer
| mysql
|
| performance_schema |
| test | +--------------------+
安裝 Python-MySQLdb
Python-MySQLdb 是一個接口程序,Python 通過它對 mysql 數(shù)據(jù)實現(xiàn)各種操作亲族。
如果要源碼安裝,可以這里下載 Python-mysqldb
sudo apt-get install build-essential Python-dev libmysqlclient-dev
sudo apt-get install Python-MySQLdb
pip安裝:
pip install mysql-Python
使用:
> import MySQLdb
SQLite
建立連接對象
> import sqlite3
> conn = sqlite3.connect("23302.db")
游標對象
> cur = conn.cursor()
- close()
- execute()
- executemany()
- fetchall()
創(chuàng)建數(shù)據(jù)庫表
> create_table = "create table book (title text, author text, lang text)"
> cur.execute(create_table)
#添加數(shù)據(jù)
> cur.execute("insert in to books values("BookName","GrayLand", "Chinese")")
>
> conn.commit()
> cur.close()
> conn.close()
查詢
> conn = sqlite3.connect(path)
> cur = conn.cursor()
> cur.execute("select * from books")
> print cur.fetchall()
>
> #批量插入
> books = [tuple(xx,xx,xx),...]
>
> cur.executemany("insert into book values (?,?,?)", books)
> conn.commit()
>
> #查詢插入結(jié)果
>
> rows = cur.execute("select * from books")
> for row in rows:
> print row
>
> ...
>
> #更新
> cur.execute("update books set title='xxx' where author='value')
> conn.commit()
>
> cur.fetchone()
> ...
> cur.fetchall()
> ...
>
> #刪除
> cur.execute("delete from books where author='xxx'")
> conn.commit()
>
>
> cur.close()
> conn.close()