爬蟲——正則表達式re模塊
為什麽要學習正則表達式
實際上爬蟲一共就四個主要步驟:
- 明確目標:需清楚目標網站
- 爬:將所有的目標網站的內容全部爬下來
- 取:在爬下來的網站內容中去掉對我們沒有用處的數據,只留取我們需要的數據
- 處理數據:按照我們想要的方式存儲和使用留取的數據
我們在前面的案例裏實際上都省略了第3步,也就是“取”的步驟。因為我們down下了的數據是全部的網頁,這些數據很龐大並且很混亂,其中大部分的東西是我們不關心的,因此我們需要將之按我們的需要過濾和匹配出來。
那麽對於文本的過濾和者規則的匹配,最強大的就是正則表達式了。
那麽什麽是正則表達式:
- 正則表達式,又稱規則表達式,通常被用來檢索、替換那些符合某個規則的文本。
- 正則表達式是對字符串操作的一種邏輯公式,就是用事先定義好的一些特定字符及這些特定字符的組合,組成一個“規則字符串”,這個“規則字符串”用來表達對字符串的一種過濾邏輯。
給定一個正則表達式和另一個字符串,我們可以達到如下的目的:
- 給定的字符串是否符合正則表達式的過濾邏輯(“匹配”)
- 通過正則表達式,從文本字符串中獲取我們想要的特定部分(“過濾”)
正則表達式規則
Python的re模塊
在Python中,我們可以使用內置的re模塊來使用正則表達式。
有一點需要特別註意的是,正則表達式使用對特殊字符進行黑底,所以如果我們要使用原始字符串,只需要加一個r前綴:r‘i love\t\.\tpython‘
re模塊的一般使用步驟如下:
- 使用compile()函數將正則表達式的字符串形式編譯為一個Pattern對象
- 通過Pattern對象提供的一系列方法對文本進行匹配查找,獲得匹配結果,一個Match對象。
- 最後使用Match對象提供的屬性和方法獲得信息,根據需要進行其他操作。
compile函數
compile函數用於編譯正則表達式,生成一個Pattern對象,它的一般使用形式如下:
#!/usr/bin/python3 # -*- conding:utf-8 -*- __author__ = ‘mayi‘ import re # 將正則表達式編譯成Pattern對象 pattern = re.compile(‘\d+‘)
在上面,我們已將一個正則表達式編譯成Pattern對象,接下來,我們就可以利用pattern的一系列方法對文本匹配查找了。
Pattern對象的一些常用方法主要有:
- match()方法:從起始位置開始查找,一次匹配
- search()方法:從任何位置開始查找,一次匹配
- findall()方法:全部匹配,返回列表
- finditer()方法:全部匹配,返回叠代器
- split()方法:分割字符串,返回列表
- sub()方法:替換
match()方法
match()方法用於查找字符串的頭部(也可以指定起始位置),它是一次匹配,只要找到了一個匹配的結果就返回,而不是查找所有匹配的結果。它的一般使用形式如下:
match(string[, pos[, endpos]])
其中,string是待匹配的字符串,pos和endpos是可選參數,指定字符串的起始和終點位置,默認值分別是0和len(string)。因此,當你不指定pos和endpos時,match()方法默認匹配字符串的頭部。
當匹配成功時,返回一個Match對象,如果沒有匹配上,則返回None。
>>> import re >>> pattern = re.compile(r‘\d+‘) # 用於匹配至少一個數字 >>> m = pattern.match(‘one12twothree34four‘) # 查找頭部,沒有匹配 >>> print m None >>> m = pattern.match(‘one12twothree34four‘, 2, 10) # 從‘e‘的位置開始匹配,沒有匹配 >>> print(m) None >>> m = pattern.match(‘one12twothree34four‘, 3, 10) # 從‘1‘的位置開始匹配,正好匹配 >>> print(m) # 返回一個 Match 對象 <_sre.SRE_Match object; span=(3, 5), match=‘12‘> >>> print(m.group(0)) # 可省略 0 12 >>> print(m.start(0)) # 可省略 0 3 >>> print(m.end(0)) # 可省略 0 5 >>> print(m.span(0)) # 可省略 0 (3, 5)
在上面,當匹配成功時返回一個Match對象,其中:
- group([group1,...])方法用於獲得一個或多個分組匹配的字符串,當要獲得整個匹配的子串時,可直接使用group()或group(0)
- start([group])方法用於獲取分組匹配的子串在整個字符串中的起始位置(子串第一個字符的索引),參數默認值為0
- end([group])方法用於獲取分組匹配的子串在整個字符串中的結束位置(子串最後一個字符的索引 + 1),參數默認值為0
- span([group])方法返回(start(group), end(group))
再看一個例子:
>>> import re >>> pattern = re.compile(r‘([a-z]+) ([a-z]+)‘, re.I) # re.I 表示忽略大小寫 >>> m = pattern.match(‘Hello World Wide Web‘) >>> print(m) # 匹配成功,返回一個 Match 對象 <_sre.SRE_Match object; span=(0, 11), match=‘Hello World‘> >>> print(m.group(0)) # 返回匹配成功的整個子串 Hello World >>> print(m.span(0)) # 返回匹配成功的整個子串的索引 (0, 11) >>> print(m.group(1)) # 返回第一個分組匹配成功的子串 Hello >>> print(m.span(1)) # 返回第一個分組匹配成功的子串的索引 (0, 5) >>> print(m.group(2)) # 返回第二個分組匹配成功的子串 World >>> print(m.span(2)) # 返回第二個分組匹配成功的子串 (6, 11) >>> print(m.groups()) # 等價於 (m.group(1), m.group(2), ...) (‘Hello‘, ‘World‘) >>> print(m.group(3)) # 不存在第三個分組 Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: no such group
search()方法
search()方法用於查找字符串的任何位置,它也是一次匹配,只要找到了一個匹配的結果就返回,而不是查找所有匹配的結果,它的一般使用形式如下:
search(string[, pos[, endpos]])
其中,string是待匹配的字符串,pos和endpos是可選參數,指定字符串的起始和終點位置,默認值分別是0和len(string)。
當匹配成功時,返回一個Match對象,如果沒有匹配上,則返回None。
如下例子:
>>> import re >>> pattern = re.compile(‘\d+‘) >>> m = pattern.search(‘one12twothree34four‘) >>> print(m) <_sre.SRE_Match object; span=(3, 5), match=‘12‘> >>> print(m.group()) 12 >>> m = pattern.search(‘one12twothree34four‘, 10, 30) >>> print(m) <_sre.SRE_Match object; span=(13, 15), match=‘34‘> >>> print(m.group()) 34 >>> print(m.span()) (13, 15)
再看一個例子:
#!/usr/bin/python3 # -*- conding:utf-8 -*- __author__ = ‘mayi‘ import re # 將正則表達式編譯成Pattern對象 pattern = re.compile(r‘\d+‘) # 使用search() 查找匹配的子串,不存在匹配的子串時,返回None m = pattern.search(‘hello 123 456 789‘) # 若這裏使用match(),返回None if m: print("matching string:", m.group()) print("position:", m.span())
執行結果:
matching string: 123 position: (6, 9)
findall()方法
上面的match()和search()方法都是一次匹配,只要找到了一個匹配的結果就返回。然而,在大多數時候,我們需要搜索整個字符串,獲得所有匹配的結果。
findall()方法的使用形式如下:
findall(string[, pos[, endpos]])
其中,string是待匹配的字符串,pos和endpos是可選參數,指定字符串的起始和終點位置,默認值分別是0和len(string)。
findall()以列表形式返回全部能匹配的子串,如果沒有匹配成功,則返回一個空列表。
如下:
>>> import re >>> pattern = re.compile(r‘\d+‘) # 匹配數字 >>> res1 = pattern.findall(‘hello 123 456 789‘) >>> res2 = pattern.findall(‘one1two2three3four4‘, 0, 16) >>> print(res1) [‘123‘, ‘456‘, ‘789‘] >>> print(res2) [‘1‘, ‘2‘, ‘3‘]
再看一個例子:
>>> import re >>> pattern = re.compile(r‘\d+\.\d+‘) # 匹配小數 >>> res = pattern.findall("3.1415926, ‘big‘, 110, 95.5") >>> print(res) [‘3.1415926‘, ‘95.5‘]
finditer()方法
finditer()方法的行為跟findall()的行為類似,也是搜索整個字符串,獲得所有匹配的結果。但它返回一個順序訪問每一個匹配結果(Match對象)的叠代器。
如下:
#!/usr/bin/python3 # -*- conding:utf-8 -*- __author__ = ‘mayi‘ import re pattern = re.compile(r‘\d+‘) res_iter1 = pattern.finditer("hello 123 456 789") res_iter2 = pattern.finditer("one1two2three3four4", 0, 16) print(res_iter1) print(res_iter2) print("res_iter1......") for m1 in res_iter1: print("matching string:{}, position:{}".format(m1.group(), m1.span())) print("res_iter2......") for m2 in res_iter2: print("matching string:{}, position:{}".format(m2.group(), m2.span()))
執行結果:
<callable_iterator object at 0x00ADF7F0> <callable_iterator object at 0x00ADF230> res_iter1...... matching string:123, position:(6, 9) matching string:456, position:(10, 13) matching string:789, position:(14, 17) res_iter2...... matching string:1, position:(3, 4) matching string:2, position:(7, 8) matching string:3, position:(13, 14)
split()方法
spilt()方法按照能夠匹配的子串將字符串分割後返回列表,它的使用形式如下:
split(string[, maxsplit])
其中,maxsplit用於指定最大分割次數,不指定將全部分割。
如下:
>>> import re >>> pattern = re.compile(r‘[\s\,\;]+‘) >>> print(pattern.split(‘a,b;; c d‘)) [‘a‘, ‘b‘, ‘c‘, ‘d‘]
sub()方法
sub()方法用於替換。它的使用形式如下:
sub(repl, string[, count])
其中,repl可以是字符串也可以是一個函數:
- 如果repl是字符串,則會使用repl去替換字符串每一個匹配的子串,並返回替換後的字符串,另外,repl還可以使用id的形式來引用分組,但不能使用編號0
- 如果repl是函數,這個方法應當只接受一個參數(Match對象),並返回一個字符串用於替換(返回的字符串中不能再引用分組)
- count用於指定最多替換次數,默認全部替換
如下:
#!/usr/bin/python3 # -*- conding:utf-8 -*- __author__ = ‘mayi‘ import re pattern = re.compile(r‘(\w+) (\w+)‘) # \w: [A-Za-z0-9] string = ‘hello 123, hello 456‘ print(pattern.sub(‘hello world‘, string)) # 我是分割線 print("*" * 30) print(pattern.sub(r‘\2 \1‘, string)) # 我是分割線 print("*" * 30) def func(m): return ‘hi ‘ + m.group(2) print(pattern.sub(func, string)) # 我是分割線 print("*" * 30) # 最多替換一次 print(pattern.sub(func, string, 1))
執行結果:
hello world, hello world ****************************** 123 hello, 456 hello ****************************** hi 123, hi 456 ****************************** hi 123, hello 456
匹配中文
在某些情況下,我們想匹配文本中的漢字,中文的unicode編碼範圍主要在[u4e00-u9fa5],這裏說主要是因為這個範圍並不完整,比如沒有包括全角(中文)標點,不過,在大部分情況下,應該是夠用的。
例如:要想把字符串s = "您好,世界。hello world!"中的中文提取出來,可以這麽做
#!/usr/bin/python3 # -*- conding:utf-8 -*- __author__ = ‘mayi‘ import re string = "你好,世界。hello world!" pattern = re.compile(r"[\u4e00-\u9fa5]+") res = pattern.findall(string) print(res)
執行結果
[‘你好‘, ‘世界‘]
爬蟲——正則表達式re模塊