u'中文'如果中文字符串在Python環(huán)境下遇到 UnicodeDecodeError,這是因?yàn)?py文件保存的格式有問題。可以在第一行添加注釋
# -*- coding: utf-8 -*-- 占位符常見的占位符有:
| %s | 字符串 |
| %d | 整數(shù) |
| %f | 浮點(diǎn)數(shù) |
| %x | 十六進(jìn)制整數(shù) |

- dict字典 {key:value,}len() 函數(shù)可以計(jì)算任意集合的大小更新dict d['Paul'] = 72迭代dict的key和value for key, value in d.items(): - set (['value'])應(yīng)用場景 weekdays = set(['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN']) 更新set add()- 1.切片: L[0:3]表示,從索引0開始取,直到索引3為止,但不包括索引3 ->>> d = {'a': 1, 'b': 2, 'c': 3}>>> for key in d:... PRint(key)判斷可迭代>>> from collections import Iterable>>> isinstance('abc', Iterable) # str是否可迭代True>>> isinstance([1,2,3], Iterable) # list是否可迭代True>>> isinstance(123, Iterable) # 整數(shù)是否可迭代False- 3.列表生成式>>> [x * x for x in range(1, 11)][1, 4, 9, 16, 25, 36, 49, 64, 81, 100]寫列表生成式時(shí),把要生成的元素x * x放到前面,后面跟for循環(huán),就可以把list創(chuàng)建出來,十分有用,多寫幾次,很快就可以熟悉這種語法。
for循環(huán)后面還可以加上if判斷,這樣我們就可以篩選出僅偶數(shù)的平方:
>>> [x * x for x in range(1, 11) if x % 2 == 0][4, 16, 36, 64, 100] - 函數(shù)filter()函數(shù)filter()根據(jù)判斷結(jié)果自動(dòng)過濾掉不符合條件的元素,返回由符合條件元素組成的新list。sorted()函數(shù)可對list進(jìn)行排序len()統(tǒng)計(jì)字符list.append('')追加元素到末尾list.pop(i)刪除i索引位置的元素range()函數(shù)range(5)生成的序列是從0開始小于5list()函數(shù)可以轉(zhuǎn)換為listadd(key)方法可以添加元素到set中remove(key)方法可以刪除元素isinstance()可以判斷一個(gè)變量的類型- get & set@property---這是關(guān)鍵字,固定格式,能讓方法當(dāng)“屬性”用。@score.setter---前面的"score"是@property緊跟的下面定義的那個(gè)方法的名字,"setter"是關(guān)鍵字,這種“@+方法名字+點(diǎn)+setter”是個(gè)固定格式與@property搭配使用。 - 模塊
1.datetime Python處理日期和時(shí)間的標(biāo)準(zhǔn)庫。 如果僅導(dǎo)入import datetime,則必須引用全名datetime.datetime。now = datetime.now() # 獲取當(dāng)前datetimedt = datetime(2015, 4, 19, 12, 20) # 用指定日期時(shí)間創(chuàng)建datetimedt.timestamp() # 把datetime轉(zhuǎn)換為timestamp把str轉(zhuǎn)換為datetime。轉(zhuǎn)換方法是通過datetime.strptime()實(shí)現(xiàn)>>> from datetime import datetime, timedelta>>> now = datetime.now()>>> nowdatetime.datetime(2015, 5, 18, 16, 57, 3, 540997)>>> now + timedelta(hours=10)datetime.datetime(2015, 5, 19, 2, 57, 3, 540997)>>> now - timedelta(days=1)datetime.datetime(2015, 5, 17, 16, 57, 3, 540997)>>> now + timedelta(days=2, hours=12)datetime.datetime(2015, 5, 21, 4, 57, 3, 540997)2.collectionsnamedtupledequedefaultdictOrderedDictCounter3.hashlib摘要算法md5計(jì)算出一個(gè)字符串的MD5值:
import hashlibmd5 = hashlib.md5()md5.update('how to use md5 in python hashlib?'.encode('utf-8'))print(md5.hexdigest())4.itertools- 面向?qū)ο?img src="http://s1.VeVb.com/20170206/n05nffvqiga13.png" alt="">
舉個(gè)例子,Python的網(wǎng)絡(luò)服務(wù)器有TCPServer、UDPServer、UnixStreamServer、UnixDatagramServer,而服務(wù)器運(yùn)行模式有 多進(jìn)程ForkingMixin 和 多線程ThreadingMixin兩種。
要?jiǎng)?chuàng)建多進(jìn)程模式的 TCPServer:
class MyTCPServer(TCPServer, ForkingMixin) pass要?jiǎng)?chuàng)建多線程模式的 UDPServer:
class MyUDPServer(UDPServer, ThreadingMixin): pass如果沒有多重繼承,要實(shí)現(xiàn)上述所有可能的組合需要 4x2=8 個(gè)子類。
- 裝飾器@property,可以將python定義的函數(shù)“當(dāng)做”屬性訪問,從而提供更加友好訪問方式 - 錯(cuò)誤、調(diào)試和測試斷言
凡是用
try: print('try...') r = 10 / 0 print('result:', r)except ZeroDivisionError as e: print('except:', e)finally: print('finally...')print('END')1.print()來輔助查看的地方,都可以用斷言(assert)來替代:IndexError: list index out of range索引越界2.File "index.py", line 11, in <module> print d['Paul']KeyError: 'Paul'字典key不存在解決:dict本身提供的一個(gè) get 方法,在Key不存在的時(shí)候,返回Nonepy->二級制文件(對語法進(jìn)行檢查)->try-except e ,continue隨機(jī)數(shù)import randomnumber= random.randint(0, 100)
- IO編程但是每次都這么寫實(shí)在太繁瑣,所以,Python引入了
with語句來自動(dòng)幫我們調(diào)用close()方法:with open('/path/to/file', 'r') as f:print(f.read()) - 進(jìn)程和線程【協(xié)程】 - 正則表達(dá)式在正則表達(dá)式中,如果直接給出字符,就是精確匹配。用
/d可以匹配一個(gè)數(shù)字,/w可以匹配一個(gè)字母或數(shù)字,所以:
'00/d'可以匹配'007',但無法匹配'00A';
'/d/d/d'可以匹配'010';
'/w/w/d'可以匹配'py3';
.可以匹配任意字符,所以:'py.'可以匹配'pyc'、'pyo'、'py!'等等。要匹配變長的字符,在正則表達(dá)式中,用
*表示任意個(gè)字符(包括0個(gè)),用+表示至少一個(gè)字符,用?表示0個(gè)或1個(gè)字符,用{n}表示n個(gè)字符,用{n,m}表示n-m個(gè)字符:來看一個(gè)復(fù)雜的例子:
/d{3}/s+/d{3,8}。我們來從左到右解讀一下:
/d{3}表示匹配3個(gè)數(shù)字,例如'010';
/s可以匹配一個(gè)空格(也包括Tab等空白符),所以/s+表示至少有一個(gè)空格,例如匹配' ',' '等;
/d{3,8}表示3-8個(gè)數(shù)字,例如'1234567'。因此我們強(qiáng)烈建議使用Python的
r前綴,就不用考慮轉(zhuǎn)義的問題了:s = r'ABC/-001'# Python的字符串# 對應(yīng)的正則表達(dá)式字符串不變:# 'ABC/-001'先看看如何判斷正則表達(dá)式是否匹配:
>>> import re>>> re.match(r'^/d{3}/-/d{3,8}$', '010-12345')<_sre.SRE_Match object; span=(0, 9), match='010-12345'>>>> re.match(r'^/d{3}/-/d{3,8}$', '010 12345')>>>
match()方法判斷是否匹配,如果匹配成功,返回一個(gè)Match對象,否則返回None。常見的判斷方法就是:test = '用戶輸入的字符串'if re.match(r'正則表達(dá)式', test):print('ok')else: print('failed') - 圖形界面 - Json- 網(wǎng)絡(luò)編程 - 訪問數(shù)據(jù)庫 - MySQL
- 框架 - BeautifulSoupBeautiful Soup自動(dòng)將輸入文檔轉(zhuǎn)換為Unicode編碼,輸出文檔轉(zhuǎn)換為utf-8編碼
soup=BeautifulSoup(html) #創(chuàng)建 beautifulsoup 對象
解析器 使用方法 優(yōu)勢 劣勢 Python標(biāo)準(zhǔn)庫 BeautifulSoup(markup, “html.parser”) Python的內(nèi)置標(biāo)準(zhǔn)庫執(zhí)行速度適中文檔容錯(cuò)能力強(qiáng) Python 2.7.3 or 3.2.2)前 的版本中文檔容錯(cuò)能力差 lxml HTML 解析器 BeautifulSoup(markup, “l(fā)xml”) 速度快文檔容錯(cuò)能力強(qiáng) 需要安裝C語言庫 lxml XML 解析器 BeautifulSoup(markup, [“l(fā)xml”, “xml”])BeautifulSoup(markup, “xml”) 速度快唯一支持XML的解析器 需要安裝C語言庫 html5lib BeautifulSoup(markup, “html5lib”) 最好的容錯(cuò)性以瀏覽器的方式解析文檔生成HTML5格式的文檔 速度慢不依賴外部擴(kuò)展 四大對象種類
Tag(通俗點(diǎn)講就是 HTML 中的一個(gè)個(gè)標(biāo)簽)NavigableStringBeautifulSoupComment1.tag:2.NavigableString獲取標(biāo)簽內(nèi)部的文字怎么辦呢?很簡單,用 .string 即可
12 print soup.title#<title>The Dormouse's story</title>
12 print soup.p.string#The Dormouse's story 遍歷文檔樹
.contents
tag 的 .content 屬性可以將tag的子節(jié)點(diǎn)以列表的方式輸出,我們可以用列表索引來獲取它的某一個(gè)元素
.children
12 print soup.head.contents[0]#<title>The Dormouse's story</title>
12 forchildin soup.body.children: print child .strings如果一個(gè)標(biāo)簽里面沒有標(biāo)簽了,那么 .string 就會返回標(biāo)簽里面的內(nèi)容。如果標(biāo)簽里面只有唯一的一個(gè)標(biāo)簽了,那么 .string 也會返回最里面的內(nèi)容,如果tag包含了多個(gè)子節(jié)點(diǎn),tag就無法確定,string 方法應(yīng)該調(diào)用哪個(gè)子節(jié)點(diǎn)的內(nèi)容, .string 的輸出結(jié)果是 None.stripped_strings 輸出的字符串中可能包含了很多空格或空行,使用
12345 <pclass="title"name="dromouse"><b>The Dormouse'sstory</b></p> <pclass="story">Once uponatime there were three little sisters;andtheir names were<aclass="sister"href="http://example.com/elsie"id="link1"><!--Elsie--></a>,<aclass="sister"href="http://example.com/lacie"id="link2">Lacie</a>and .stripped_strings可以去除多余空白內(nèi)容.parent (有點(diǎn)像pwd)
123456789101112 forstringinsoup.stripped_strings: print(repr(string)) # u"The Dormouse's story" # u"The Dormouse's story" # u'Once upon a time there were three little sisters; and their names were' # u'Elsie' # u',' # u'Lacie' # u'and' # u'Tillie' # u';/nand they lived at the bottom of a well.' # u'...'
123 p=soup.pprintp.parent.name#body 搜索文檔樹
方法一:find_all( name , attrs , recursive , text , **kwargs )
name參數(shù)可以查找所有名字為name的tag下面方法校驗(yàn)了當(dāng)前元素,如果包含
class屬性卻不包含id屬性,那么將返回True:
12 def has_class_but_no_id(tag): returntag.has_attr('class')andnottag.has_attr('id') 將這個(gè)方法作為參數(shù)傳入
find_all()方法,將得到所有<p>標(biāo)簽:keyWord 參數(shù)
1234 soup.find_all(has_class_but_no_id)# [<p class="title"><b>The Dormouse's story</b></p>,# <p class="story">Once upon a time there were...</p>,# <p class="story">...</p>]
12 soup.find_all(id='link2')# [<a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>] 如果傳入
href參數(shù),Beautiful Soup會搜索每個(gè)tag的”href”屬性
12 soup.find_all(href=re.compile("elsie"))# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>] 使用多個(gè)指定名字的參數(shù)可以同時(shí)過濾tag的多個(gè)屬性
12 soup.find_all(href=re.compile("elsie"),id='link1')# [<a class="sister" href="http://example.com/elsie" id="link1">three</a>] 在這里我們想用 class 過濾,不過 class 是 python 的關(guān)鍵詞,這怎么辦?加個(gè)下劃線就可以
1234 soup.find_all("a",class_="sister")# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>,# <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>] 有些tag屬性在搜索不能使用,比如HTML5中的 data-* 屬性
123 data_soup=BeautifulSoup('<div data-foo="value">foo!</div>')data_soup.find_all(data-foo="value")# SyntaxError: keyword can't be an expression 但是可以通過
find_all()方法的attrs參數(shù)定義一個(gè)字典參數(shù)來搜索包含特殊屬性的taglimit 參數(shù)
12 data_soup.find_all(attrs={"data-foo":"value"})# [<div data-foo="value">foo!</div>]
123 soup.find_all("a",limit=2)# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>,# <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>] (2)find( name , attrs , recursive , text , **kwargs )
它與 find_all() 方法唯一的區(qū)別是
方法二:find_all()方法的返回結(jié)果是值包含一個(gè)元素的列表,而find()方法直接返回結(jié)果CSS選擇器
soup.select(),返回類型是 listsoup=BeautifulSoup(html,'lxml')print type(soup.select('title'))print soup.select('title')[0].get_text() fortitle insoup.select('title'): print title.get_text()以上的 select 方法返回的結(jié)果都是列表形式,可以遍歷形式輸出,然后用 get_text() 方法來獲取它的內(nèi)容。 - 其他if-elif-else迭代:enumerate() 函數(shù):自動(dòng)把每個(gè)元素變成 (index, element) 這樣的tuple,再迭代,就同時(shí)獲得了索引和元素本身。[x * x for x in range(1, 11) if x % 2 == 0]傳入**kw 即可傳入任意數(shù)量的參數(shù),并通過 setattr() 綁定屬性,iteritems()用于字典kw的遍歷
參考代碼:
class Person(object): def __init__(self, name, gender, **kw): self.name = name self.gender = gender for k, v in kw.iteritems(): setattr(self, k, v)p = Person('Bob', 'Male', age=18, course='Python')print p.ageprint p.course
|
新聞熱點(diǎn)
疑難解答
圖片精選