u'中文'如果中文字符串在Python環(huán)境下遇到 UnicodeDecodeError,這是因為.py文件保存的格式有問題。可以在第一行添加注釋
# -*- coding: utf-8 -*-- 占位符常見的占位符有:
%s | 字符串 |
%d | 整數(shù) |
%f | 浮點數(shù) |
%x | 十六進制整數(shù) |
應用場景 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]
寫列表生成式時,把要生成的元素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ù)判斷結果自動過濾掉不符合條件的元素,返回由符合條件元素組成的新list。sorted()函數(shù)可對list進行排序len()統(tǒng)計字符list.append('')追加元素到末尾list.pop(i)刪除i索引位置的元素
range()
函數(shù)range(5)
生成的序列是從0開始小于5list()
函數(shù)可以轉換為listadd(key)
方法可以添加元素到set中remove(key)
方法可以刪除元素isinstance()可以判斷一個變量的類型- get & set@property---這是關鍵字,固定格式,能讓方法當“屬性”用。@score.setter---前面的"score"是@property緊跟的下面定義的那個方法的名字,"setter"是關鍵字,這種“@+方法名字+點+setter”是個固定格式與@property搭配使用。 - 模塊
1.datetime Python處理日期和時間的標準庫。 如果僅導入
import datetime
,則必須引用全名datetime.datetime
。now = datetime.now() # 獲取當前datetime
dt = datetime(2015, 4, 19, 12, 20) # 用指定日期時間創(chuàng)建datetime
dt.timestamp() # 把datetime轉換為timestamp把str轉換為datetime。轉換方法是通過
datetime.strptime()
實現(xiàn)>>> from datetime import datetime, timedelta
>>> now = datetime.now()
>>> now
datetime.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計算出一個字符串的MD5值:
import hashlib
md5 = hashlib.md5()
md5.update('how to use md5 in python hashlib?'.encode('utf-8'))
print(md5.hexdigest())
4.itertools
- 面向對象
舉個例子,Python的網絡服務器有TCPServer、UDPServer、UnixStreamServer、UnixDatagramServer,而服務器運行模式有 多進程ForkingMixin 和 多線程ThreadingMixin兩種。
要創(chuàng)建多進程模式的 TCPServer:
class MyTCPServer(TCPServer, ForkingMixin) pass要創(chuàng)建多線程模式的 UDPServer:
class MyUDPServer(UDPServer, ThreadingMixin): pass如果沒有多重繼承,要實現(xiàn)上述所有可能的組合需要 4x2=8 個子類。
- 裝飾器@property,可以將python定義的函數(shù)“當做”屬性訪問,從而提供更加友好訪問方式 - 錯誤、調試和測試斷言
凡是用
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本身提供的一個 get 方法,在Key不存在的時候,返回Nonepy->二級制文件(對語法進行檢查)->try-except e ,continue隨機數(shù)import randomnumber= random.randint(0, 100)
- IO編程但是每次都這么寫實在太繁瑣,所以,Python引入了
with
語句來自動幫我們調用close()
方法:with open('/path/to/file', 'r') as f:print(f.read()) - 進程和線程【協(xié)程】 - 正則表達式
在正則表達式中,如果直接給出字符,就是精確匹配。用
/d
可以匹配一個數(shù)字,/w
可以匹配一個字母或數(shù)字,所以:
'00/d'
可以匹配'007'
,但無法匹配'00A'
;
'/d/d/d'
可以匹配'010'
;
'/w/w/d'
可以匹配'py3'
;
.
可以匹配任意字符,所以:'py.'
可以匹配'pyc'
、'pyo'
、'py!'
等等。要匹配變長的字符,在正則表達式中,用
*
表示任意個字符(包括0個),用+
表示至少一個字符,用?
表示0個或1個字符,用{n}
表示n個字符,用{n,m}
表示n-m個字符:來看一個復雜的例子:
/d{3}/s+/d{3,8}
。我們來從左到右解讀一下:
/d{3}
表示匹配3個數(shù)字,例如'010'
;
/s
可以匹配一個空格(也包括Tab等空白符),所以/s+
表示至少有一個空格,例如匹配' '
,' '
等;
/d{3,8}
表示3-8個數(shù)字,例如'1234567'
。因此我們強烈建議使用Python的
r
前綴,就不用考慮轉義的問題了:s = r'ABC/-001'# Python的字符串# 對應的正則表達式字符串不變:# 'ABC/-001'
先看看如何判斷正則表達式是否匹配:
>>> 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()
方法判斷是否匹配,如果匹配成功,返回一個Match
對象,否則返回None
。常見的判斷方法就是:test = '用戶輸入的字符串'if re.match(r'正則表達式', test):print('ok')else: print('failed') - 圖形界面 - Json
- 網絡編程 - 訪問數(shù)據(jù)庫 - MySQL
- 框架 - BeautifulSoupBeautiful Soup自動將輸入文檔轉換為Unicode編碼,輸出文檔轉換為utf-8編碼
soup=BeautifulSoup(html) #創(chuàng)建 beautifulsoup 對象
解析器 使用方法 優(yōu)勢 劣勢 Python標準庫 BeautifulSoup(markup, “html.parser”) Python的內置標準庫執(zhí)行速度適中文檔容錯能力強 Python 2.7.3 or 3.2.2)前 的版本中文檔容錯能力差 lxml HTML 解析器 BeautifulSoup(markup, “l(fā)xml”) 速度快文檔容錯能力強 需要安裝C語言庫 lxml XML 解析器 BeautifulSoup(markup, [“l(fā)xml”, “xml”])BeautifulSoup(markup, “xml”) 速度快唯一支持XML的解析器 需要安裝C語言庫 html5lib BeautifulSoup(markup, “html5lib”) 最好的容錯性以瀏覽器的方式解析文檔生成HTML5格式的文檔 速度慢不依賴外部擴展 四大對象種類
Tag(通俗點講就是 HTML 中的一個個標簽)
NavigableString
BeautifulSoup
Comment
1.tag:2.NavigableString獲取標簽內部的文字怎么辦呢?很簡單,用 .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é)點以列表的方式輸出,我們可以用列表索引來獲取它的某一個元素
.children
12 print soup.head.contents[0]#<title>The Dormouse's story</title>
12 forchildin soup.body.children: print child .strings如果一個標簽里面沒有標簽了,那么 .string 就會返回標簽里面的內容。如果標簽里面只有唯一的一個標簽了,那么 .string 也會返回最里面的內容,如果tag包含了多個子節(jié)點,tag就無法確定,string 方法應該調用哪個子節(jié)點的內容, .string 的輸出結果是 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
可以去除多余空白內容.parent (有點像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下面方法校驗了當前元素,如果包含
class
屬性卻不包含id
屬性,那么將返回True
:
12 def has_class_but_no_id(tag): returntag.has_attr('class')andnottag.has_attr('id') 將這個方法作為參數(shù)傳入
find_all()
方法,將得到所有<p>標簽: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會搜索每個tag的”href”屬性
12 soup.find_all(href=re.compile("elsie"))# [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>] 使用多個指定名字的參數(shù)可以同時過濾tag的多個屬性
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 的關鍵詞,這怎么辦?加個下劃線就可以
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ù)定義一個字典參數(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()
方法的返回結果是值包含一個元素的列表,而find()
方法直接返回結果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 方法返回的結果都是列表形式,可以遍歷形式輸出,然后用 get_text() 方法來獲取它的內容。 - 其他if-elif-else迭代:enumerate() 函數(shù):自動把每個元素變成 (index, element) 這樣的tuple,再迭代,就同時獲得了索引和元素本身。[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
新聞熱點
疑難解答