常用
賦值
列表推導式
列表解析表達式,類似[i*2 for i in list]
三元運算
1 if 5>3 else 0
輸出1
占位符
print "打印數(shù)字參數(shù)num %d" %(num)
整數(shù):%d
,浮點數(shù):%f
,字符串:%s
,萬能格式:%r
yield
yield 是一個類似 return 的關鍵字,只是這個函數(shù)返回的是個生成器。
生成器是可以迭代的,但是你 只可以讀取它一次 ,因為它并不把所有的值放在內(nèi)存中,它是實時地生成數(shù)據(jù):
#[]生成list,()生成生成器
mygenerator = (x*x for x in range(3))
for i in mygenerator:
print i
數(shù)據(jù)結構
tuple元組
Python的元組與列表類似,不同之處在于元組的元素不能修改。
tup1 = ('physics', 'chemistry', 1997, 2000)
字典
遍歷
dict={"name":"python","english":33,"math":35}
print "##for in "
for i in dict:
print "dict[%s]=" % i,dict[i]
print "##items"
for (k,v) in dict.items():
print "dict[%s]=" % k,v
print "##iteritems"
for k,v in dict.iteritems():
print "dict[%s]=" % k,v
dict1.update(dict2)
將dict2的鍵值對更新到dict1
判斷key是否存在
d = dict{'name':'bob','value':'5'}
#1
print d.has_key('name') #True
#2
print 'name' in d.keys() #True
合并
x = {'apple':1,'banana':2}
y = {'banana':10,'pear':11}
for k, v in y.items():
if k in x.keys():
x[k] += v
else:
x[k] = v
#>>>x {'pear':11,'apple':1,'banana':12}
list
list合并
list1+list2
list1.extend(list2)
去重
list(set(list1))
list相減
先轉化為set相減,再list化
newlist = list(set(list1) - set(list2))
list元素重復次數(shù)
my_dict = {i:MyList.count(i) for i in MyList}
list批量更新
list.extend(addlist)
遍歷兩個list
把兩個list合并之后再遍歷
list1 = ['a','b','c']
list2 = [1,2,3]
list = zip(list1,list2)
#[('a',1),('b',2'),('c',3)]
for i,j in list:
獲取一個隨機子list
rand_items = [items[random.randrange(len(items))] for item in range(4)]
# 或者
rand_items = random.sample(items, n)
混淆排序用random.shuffle
set 集合批量更新和更新
a = list[]
b = set(a)
b.update(list)
b.add('x')
list.pop()
刪除最后一個元素并返回該元素的值
常用函數(shù)
數(shù)學運算
取整
import math
#三個取整返回結果都是浮點數(shù)
math.ceil(2.3) #向上取整 3.0
math.floor(2.3) #向下取整 2.0
math.round(2.3) #四舍五入 2.0
多進程 多線程
多進程
感覺是用于重復執(zhí)行同一個任務
標準庫:Multiprocessing
python進程池:multiprocessing.pool
廖雪峰:python進程
Python多進程模塊Multiprocessing介紹
相關閱讀GIL
據(jù)說用Gevent替代更好4
多線程
感覺是用于同事執(zhí)行一個任務中不同的子任務
張亞楠:線程池threadpool
threadpool github主頁,比pip新
threading
setDaemon(True)
表示這個進程不重要,主線程不許要等待setDaemon(True)
的子線程,可直接退出,如果要等待子進程完成后再退出,那么就不要設置或者顯式設置setDaemon(False)
(使用進程便利文本的時候,設置為True可能導致最后結果偏少,因為主要進程過早結束了)
join()
會等到線程結束,或者給了timeout參數(shù)的時候,等到超時。如果主線程除了等線程結束之外還有其他事要做,就不需要調(diào)用join()
,只有在你要等待線程結束的時候才調(diào)用join()
(http://honglei.blog.51cto.com/3143746/933118)(PS:但不調(diào)用會死鎖???)
queue
http://python.usyiyi.cn/python_278/library/queue.html
queue.join()
等到queue為空,再執(zhí)行別的操作
線程退出
1.class的構造器中添加:
self.setDaemon(True)
2.run()中添加queue.task_done() 告知程序這個queue操作完成(例如循環(huán)中queue取數(shù)據(jù)一次)
3.主線程中添加queue.join() 等待queue為空,就執(zhí)行后續(xù)操作
進階 協(xié)程 gevent 待補充
文件和路徑
重命名:os.rename(old, new)
刪除:os.remove(file)
列出目錄下的文件 :os.listdir(path)
獲取當前工作目錄:os.getcwd()
改變工作目錄:os.chdir(newdir)
創(chuàng)建多級目錄:os.makedirs(r"c:\python \test")
創(chuàng)建單個目錄:os.mkdir("test")
刪除多個目錄:os.removedirs(r"c:\python") #刪除所給路徑最后一個目錄下所有空目錄。
刪除單個目錄:os.rmdir("test")
獲取文件屬性:os.stat(file)
修改文件權限與時間戳:os.chmod(file)
執(zhí)行操作系統(tǒng)命令:os.system("dir")
啟動新進程:os.exec(), os.execvp()
在后臺執(zhí)行程序:osspawnv()
終止當前進程:os.exit(), os._exit()
分離文件名:os.path.split(r"c:\python\hello.py") --> ("c:\python", "hello.py")
分離擴展名:os.path.splitext(r"c:\python\hello.py") --> ("c:\python\hello", ".py")
獲取路徑名:os.path.dirname(r"c:\python\hello.py") --> "c:\python"
獲取文件名:os.path.basename(r"r:\python\hello.py") --> "hello.py"
判斷文件或目錄是否存在:os.path.exists(r"c:\python\hello.py") --> True
判斷是否是絕對路徑:os.path.isabs(r".\python") --> False
判斷是否是目錄:os.path.isdir(r"c:\python") --> True
判斷是否是文件:os.path.isfile(r"c:\python\hello.py") --> True
判斷是否是鏈接文件:os.path.islink(r"c:\python\hello.py") --> False
獲取文件大小:os.path.getsize(filename)
搜索目錄下的所有文件:os.path.walk()
csv操作
錯誤
ValueError: too many values to unpack split
如果行格式異常,i,j,k=line.split(',')
就會報錯,用異常處理跳過就好
for line in open('csvname.csv'){
i,j,k = line.split(',')
}
序列化和反序列化
json
#對象轉json
import json
d = dict(name='Bob', age=20, score=88)
json.dumps(d)
#反序列化
json_str = '{"age":20, "score":88, "name": "Bob"}'
json.loads(json_str)
讀取scrapy的jsonlines文件
import json
lines = []
with open('lines.json','r') as f:
for line in f:
lines.append(json.loads(line))
寫入包含中文的json到文件
python的json.dumps方法默認會輸出成這種格式"\u535a\u5ba2\u56ed",
要輸出中文需要指定ensure_ascii參數(shù)為False,去掉indent參數(shù)就是單行,如下代碼片段:
json.dumps({'text':"中文"},ensure_ascii=False,indent=2)
pickle
#cPickle速度比pickle快
try:
import cPickle as pickle
except ImportError:
import pickle
#序列化
import pickle
table = {
'a':[1,2,3],
'b':['span','eggs'],
'c':{'name':'bob'}
}
mydb = open('dbase','w')
pickle.dump(table,mydb)
mydb.close()
#反序列化
mydb = open('dbase','r')
table = pickle.load(mydb)
shelve
shelve的鍵必須是字符串,而值可以是python中任意的數(shù)值類型,以鍵值對的形式把對象序列化到文件
#存數(shù)據(jù)
import shelve
dbase = shelve.open('mydbase')
object1 = ['The','bright',('side','of'),['life']]
object2 = {'name':'Brian','age':33,'motto':object1}
dbase['brian'] = object2
dbase['knight'] = {'name':'Knight','motto':'Ni!'}
dbase close()
#
#取數(shù)據(jù)
dbase = shelve.open("mydbase")
len(dbase) #2#
dbase.keys() #['knight','brian']#
dbase['knight'] #{'motto':'Ni!','name':'Knight'}#
sql
sql插入時間
import time
a = time.strptime('my date', "%b %d %Y %H:%M")
cursor.execute('INSERT INTO myTable (Date) VALUES(%s)', (time.strftime('%Y-%m-%d %H:%M:%S', a),))
import datetime
a = datetime.datetime.strptime('my date', "%b %d %Y %H:%M")
cursor.execute('INSERT INTO myTable (Date) VALUES(%s)', (a.strftime('%Y-%m-%d %H:%M:%S'),))
sql select list, where ... in 列表
http://blog.rizauddin.com/2008/11/python-list-in-sql-query-as-parameter_7496.html
id = [10, 20, 4, 6, 9]
sql = 'select * from studens where id in %s' % str(tuple(id))
id = [10, 20, 4, 6, 9]
xx = ', '.join(id)
sql = 'select * from students where id in (%s)' % xx
postgresql
http://www.yiibai.com/html/postgresql/2013/080998.html
import psycopg2
conn = psycopg2.connect("database="testdb",user="postgres",password="password",host="127.0.0.1",port="5432")
cur = conn.cursor()
cur.execute('''sql''')
conn.commit()
conn.close()
connection url
postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]
postgresql://
postgresql://localhost
postgresql://localhost:5433
postgresql://localhost/mydb
postgresql://user@localhost
postgresql://user:secret@localhost
postgresql://other@localhost/otherdb?connect_timeout=10&application_name=myapp
postgresql插入中文list
#單個list
dbtag = [u'\u52a8\u753b',u'\u52a8\u753b',u'\u52a8\u753b']
cur.execute("""insert into doubansimple(dbtag) values(%s) """ , [dbtag])
# cur.mogrify可以測試語句,并翻譯成最終提交的sql語句
#多參數(shù),包含list,json
cur.mogrify('''insert into douban(title, htitle, dbid, dbtag, dbrating, mainpic, desc_info, info_pic, staff_info, staff, related_info, related_pic) VALUES( %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)''', (title, htitle, dbid, dbtag, dbrating, mainpic, desc_info, info_pic, staff_info, staff, related_info, related_pic))
postgres 注意用戶對表空間的權限
正則
r = re.compile(r'regex', re.MULTILINE)
r.sub("",str)
#等價于
re.sub(r'regex',"",str, flag=re.MULTILINE)
re.sub引用
p = re.compile(r'(\w+) (\w+)')
s = 'i say, hello world!'
print p.subn(r'\2 \1', s)
# ('say i, world hello!', 2)
一次完成多個替換
http://book.51cto.com/art/201005/198272.htm
import re
def multiple_replace(text, adict):
rx = re.compile('|'.join(map(re.escape, adict)))
def one_xlat(match):
return adict[match.group(0)]
return rx.sub(one_xlat, text)
import re
def make_xlat(*args, **kwds):
adict = dict(*args, **kwds)
rx = re.compile('|'.join(map(re.escape, adict)))
def one_xlat(match):
return adict[match.group(0)]
def xlat(text):
return rx.sub(one_xlat, text)
return xlat
使用 詳細區(qū)別看上面鏈接(待看)
if _ _name_ _ == "_ _main_ _":
text = "Larry Wall is the creator of Perl"
adict = {
"Larry Wall" : "Guido van Rossum",
"creator" : "Benevolent Dictator for Life",
"Perl" : "Python",
}
print multiple_replace(text, adict)
translate = make_xlat(adict)
print translate(text)
搜索
re.search(r'regex',str)
# 等價于
r = re.compile(r'regex')
r.search("",str)
search
匹配所有字符串,最多匹配一次,返回一個match對象,用match.group()
獲取值
match
從字符串的開始匹配一次,返回match
,開始不同,匹配就失敗,返貨None
findall
返回所有匹配的字符串列表
字符和編碼
http://www.lxweimin.com/p/53bb448fe85b
codecs指定編碼打開文件和創(chuàng)建文件
codecs.open('filename.txt','ab+','utf-8')
編碼轉換
編碼查詢
isinstance(s, str)
isinstance(s, unicode)
返回True or False
字符串 字符串處理
str.strip()
,用于去除字符串頭尾的指定字符,默認去除空格
str.splie('/')[1]
,分割字符串為list
str.replace("aabb","")
替換aabb為空字符串(刪除)
urlencode和urldecode
將鏈接中已編碼的字符串顯示成正常文字,中文unquote成gbk。
str = urllib.unquote(str).encode('utf8')
urlencode編碼unquote之后輸出有問題
urllib.unquote(split_link[2].decode('utf-8').encode('utf-8')).decode("utf-8")
將字符串編碼
str = urllib.quote(str)
將鍵值對編碼用urlencode
,解碼還是用unquote
from urllib import urlencode, urldecode
data = {
'a':'text',
'name':'魔獸'
}
encodedata = urlencode(data)
unicode uft-8
unicode可以編碼成utf-8
ustr = u' \u65e5\u672c'
ustr.encode('utf8')
從unicode或utf編碼轉換成漢字
寫入文件的時候用的到
string_escape
和 unicode_escape
可以轉換utf8和unicode
f = '\u53eb\u6211'
print f
print (f.decode('unicode_escape'))
#結果為:
# \u53eb\u6211
# 叫我
json.dumps()之后轉utf8
json.dumps(dict)
之后,編碼可能會變?yōu)閡nicode字符串
json.dumps(dict).decode('unicode_escape').encode('utf-8')
數(shù)據(jù)庫和終端編碼查詢
json寫入數(shù)據(jù)庫
寫入之前先反序列化 json.dumps(dict)
python終端編碼
print sys.stdout.encoding
postgresql終端編碼
查看服務端編碼
show server_encoding
查看終端當前的編碼
show client_encoding
設置編碼
\encoding CLIENT-ENCODING
windows
cmd默認編碼是gbk
sqlite當前編碼格式
pragma encoding
多線程 queue
queue去重
繼承queue,重寫方法,達到去重效果
http://stackoverflow.com/questions/16506429/check-if-element-is-already-in-a-queue/16506527#16506527
class SetQueue(Queue.Queue):
def _init(self, maxsize):
self.queue = set()
def _put(self, item):
self.queue.add(item)
def _get(self):
return self.queue.pop()
異常處理
- 可以用條件判斷加上raise主動跳轉到except:
- raise 如果跟上提示或者具體的異常,則會直接報錯,不會跳轉到except
- try... except... else
常用庫
requests庫
快速上手
高級用法
requests下載圖片
request和urllib2下載圖片
忽略ssl證書驗證,在get方法添加verify=False
連接數(shù)過多 Failed to establish a new connection headers={'Connection':'close'})
傳遞參數(shù)字典 get時可以用params=,post時用data=,其他還有json=等
bs4
Python中過濾HTML標簽的函數(shù)
https://gist.github.com/dndn/859717
#用正則簡單過濾html的<>標簽
import re
str = "<img /><a>srcd</a>hello</br><br/>"
str = re.sub(r'</?\w+[^>]*>','',str)
#改進版 去除script
str = re.sub(r'(<script.*?</script>)|(<!?/?[^>]+>)|(&\w{4};)','',html,flags=re.DOTALL)
print str
#用了HTMLParser,有更簡單的方式嗎?正則?
def strip_tags(html):
"""
Python中過濾HTML標簽的函數(shù)
>>> str_text=strip_tags("<font color=red>hello</font>")
>>> print str_text
hello
"""
from HTMLParser import HTMLParser
html = html.strip()
html = html.strip("\n")
result = []
parser = HTMLParser()
parser.handle_data = result.append
parser.feed(html)
parser.close()
return ''.join(result)
pip批量安裝依賴
pip install -r requirements.txt
生成隨機值
隨機字母列表
http://stackoverflow.com/questions/306400/how-do-i-randomly-select-an-item-from-a-list-using-python
import random
foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))
隨機數(shù)字列表
http://stackoverflow.com/questions/16655089/python-random-numbers-into-a-list
#1-100范圍
import random
my_randoms = random.sample(xrange(1, 101), 10)
獲取文件列表 按創(chuàng)建時間排列
性能優(yōu)化
測量小代碼執(zhí)行時間 timeit
http://python.usyiyi.cn/python_278/library/timeit.html
變量占用空間大小
http://outofmemory.cn/code-snippet/1776/Python-how-look-variable-involve-space-size