1. 程式人生 > >Python爬蟲開發【第1篇】【正則表達式】

Python爬蟲開發【第1篇】【正則表達式】

返回 true ccf color arch iter 子串 call last

1、正則表達式

  它是對字符串操作的一種邏輯公式,就是用事先定義好的一些特定字符、及這些特定字符的組合,組成一個“規則字符串”,這個“規則字符串”用來表達對字符串的一種過濾邏輯。

技術分享圖片

2、re模塊

2.1、re模塊使用步驟:

  1. 使用 compile() 函數將正則表達式的字符串形式編譯為一個 Pattern 對象

  2. 通過 Pattern 對象提供的一系列方法對文本進行匹配查找,獲得匹配結果,一個 Match 對象。

  3. 最後使用 Match 對象提供的屬性和方法獲得信息,根據需要進行其他的操作

2.2、compile()

   compile 函數用於編譯正則表達式,生成一個 Pattern 對象,它的一般使用形式如下:

import re

# 將正則表達式編譯成 Pattern 對象
pattern = re.compile(r‘\d+‘)

Pattern 對象的一些常用方法主要有:

  • match 方法:從起始位置開始查找,一次匹配
  • search 方法:從任何位置開始查找,一次匹配
  • findall 方法:全部匹配,返回列表
  • finditer 方法:全部匹配,返回叠代器
  • split 方法:分割字符串,返回列表
  • sub 方法:替換

2.2.1、match方法:

  match 方法用於查找字符串的頭部(也可以指定起始位置),它是一次匹配,只要找到了一個匹配的結果就返回,而不是查找所有匹配的結果。

  它的一般使用形式如下:match(string[, pos[, endpos]])

  其中,string 是待匹配的字符串,pos 和 endpos 是可選參數,指定字符串的起始和終點位置,默認值分別是 0 和 len (字符串長度)。因此,

  當你不指定 pos 和 endpos 時,match 方法默認匹配字符串的頭部。

  當匹配成功時,返回一個 Match 對象,如果沒有匹配上,則返回 None。 

例1:

>>> 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 at 0x10a42aac0> >>> m.group(0) # 可省略 0 ‘12‘ >>> m.start(0) # 可省略 0 3 >>> m.end(0) # 可省略 0 5 >>> m.span(0) # 可省略 0 (3, 5) group([group1, …]) 方法用於獲得一個或多個分組匹配的字符串,當要獲得整個匹配的子串時,可直接使用 group() 或 group(0); start([group]) 方法用於獲取分組匹配的子串在整個字符串中的起始位置(子串第一個字符的索引),參數默認值為 0; end([group]) 方法用於獲取分組匹配的子串在整個字符串中的結束位置(子串最後一個字符的索引+1),參數默認值為 0; span([group]) 方法返回 (start(group), end(group))。


例2:
>>> 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 at 0x10bea83e8> >>> m.group(0) # 返回匹配成功的整個子串 ‘Hello World‘ >>> m.span(0) # 返回匹配成功的整個子串的索引 (0, 11) >>> m.group(1) # 返回第一個分組匹配成功的子串 ‘Hello‘ >>> m.span(1) # 返回第一個分組匹配成功的子串的索引 (0, 5) >>> m.group(2) # 返回第二個分組匹配成功的子串 ‘World‘ >>> m.span(2) # 返回第二個分組匹配成功的子串 (6, 11) >>> m.groups() # 等價於 (m.group(1), m.group(2), ...) (‘Hello‘, ‘World‘) >>> m.group(3) # 不存在第三個分組 Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: no such group

2.2.2、Search方法  

  search 方法用於查找字符串的任何位置,它也是一次匹配,只要找到了一個匹配的結果就返回,而不是查找所有匹配的結果,

  它的一般使用形式如下:search(string[, pos[, endpos]])

  其中,string 是待匹配的字符串,pos 和 endpos 是可選參數,指定字符串的起始和終點位置,默認值分別是 0 和 len (字符串長度)。

  當匹配成功時,返回一個 Match 對象,如果沒有匹配上,則返回 None。

例1:
>>> import re
>>> pattern = re.compile(‘\d+‘)
>>> m = pattern.search(‘one12twothree34four‘)  # 這裏如果使用 match 方法則不匹配
>>> m
<_sre.SRE_Match object at 0x10cc03ac0>
>>> m.group()
‘12‘
>>> m = pattern.search(‘one12twothree34four‘, 10, 30)  # 指定字符串區間
>>> m
<_sre.SRE_Match object at 0x10cc03b28>
>>> m.group()
‘34‘
>>> m.span()
(13, 15)

例2:
# -*- coding: utf-8 -*-

import re
# 將正則表達式編譯成 Pattern 對象
pattern = re.compile(r‘\d+‘)
# 使用 search() 查找匹配的子串,不存在匹配的子串時將返回 None
# 這裏使用 match() 無法成功匹配
m = pattern.search(‘hello 123456 789‘)
if m:
    # 使用 Match 獲得分組信息
    print ‘matching string:‘,m.group()
    # 起始位置和結束位置
    print ‘position:‘,m.span()
執行結果:

matching string: 123456
position: (6, 12)

2.2.3、findall方法

  findall可以搜索整個字符串,獲得所有匹配的結果。

  findall 方法的使用形式如下:findall(string[, pos[, endpos]])

  其中,string 是待匹配的字符串,pos 和 endpos 是可選參數,指定字符串的起始和終點位置,默認值分別是 0 和 len (字符串長度)。

  findall 以列表形式返回全部能匹配的子串,如果沒有匹配,則返回一個空列表。

例1:
import re
pattern = re.compile(r‘\d+‘)   # 查找數字

result1 = pattern.findall(‘hello 123456 789‘)
result2 = pattern.findall(‘one1two2three3four4‘, 0, 10)

print result1
print result2
執行結果:

[‘123456‘, ‘789‘]
[‘1‘, ‘2‘]

例2:
# re_test.py

import re

#re模塊提供一個方法叫compile模塊,提供我們輸入一個匹配的規則
#然後返回一個pattern實例,我們根據這個規則去匹配字符串
pattern = re.compile(r‘\d+\.\d*‘)

#通過partten.findall()方法就能夠全部匹配到我們得到的字符串
result = pattern.findall("123.141593, ‘bigcat‘, 232312, 3.15")

#findall 以 列表形式 返回全部能匹配的子串給result
for item in result:
    print item
運行結果:

123.141593
3.15

2.2.4、finditer方法

  finditer 方法的行為跟 findall 的行為類似,也是搜索整個字符串,獲得所有匹配的結果。但它返回一個順序訪問每一個匹配結果(Match 對象)的叠代器。

# -*- coding: utf-8 -*-

import re
pattern = re.compile(r‘\d+‘)

result_iter1 = pattern.finditer(‘hello 123456 789‘)
result_iter2 = pattern.finditer(‘one1two2three3four4‘, 0, 10)

print type(result_iter1)
print type(result_iter2)

print ‘result1...‘
for m1 in result_iter1:   # m1 是 Match 對象
    print ‘matching string: {}, position: {}‘.format(m1.group(), m1.span())

print ‘result2...‘
for m2 in result_iter2:
    print ‘matching string: {}, position: {}‘.format(m2.group(), m2.span())
執行結果:

<type ‘callable-iterator‘>
<type ‘callable-iterator‘>
result1...
matching string: 123456, position: (6, 12)
matching string: 789, position: (13, 16)
result2...
matching string: 1, position: (3, 4)
matching string: 2, position: (7, 8)

2.2.5、spilt方法

  split 方法按照能夠匹配的子串將字符串分割後返回列表,

  它的使用形式如下:split(string[, maxsplit])

  其中,maxsplit 用於指定最大分割次數,不指定將全部分割。

import re
p = re.compile(r‘[\s\,\;]+‘)
print p.split(‘a,b;; c   d‘)
執行結果:

[‘a‘, ‘b‘, ‘c‘, ‘d‘]

2.2.6、sub方法

  sub 方法用於替換。

  它的使用形式如下:sub(repl, string[, count])

  其中,repl 可以是字符串也可以是一個函數:

    • 如果 repl 是字符串,則會使用 repl 去替換字符串每一個匹配的子串,並返回替換後的字符串,另外,repl 還可以使用 id 的形式來引用分組,但不能使用編號 0;

    • 如果 repl 是函數,這個方法應當只接受一個參數(Match 對象),並返回一個字符串用於替換(返回的字符串中不能再引用分組)。

    • count 用於指定最多替換次數,不指定時全部替換。
import re
p = re.compile(r‘(\w+) (\w+)‘) # \w = [A-Za-z0-9]
s = ‘hello 123, hello 456‘

print p.sub(r‘hello world‘, s)  # 使用 ‘hello world‘ 替換 ‘hello 123‘ 和 ‘hello 456‘
print p.sub(r‘\2 \1‘, s)        # 引用分組

def func(m):
    return ‘hi‘ + ‘ ‘ + m.group(2)

print p.sub(func, s)
print p.sub(func, s, 1)         # 最多替換一次
執行結果:

hello world, hello world
123 hello, 456 hello
hi 123, hi 456
hi 123, hello 456

2.2.7、匹配中文

假設現在想把字符串 title = u‘你好,hello,世界‘ 中的中文提取出來,可以這麽做:

import re

title = u‘你好,hello,世界‘
pattern = re.compile(ur‘[\u4e00-\u9fa5]+‘)
result = pattern.findall(title)

print result

正則表達式前面加上了兩個前綴 ur,其中 r 表示使用原始字符串,u 表示是 unicode 字符串。 執行結果: [u‘\u4f60\u597d‘, u‘\u4e16\u754c‘]

3、貪婪模式與非貪婪模式

  • 貪婪模式:在整個表達式匹配成功的前提下,盡可能多的匹配 ( * );
  • 非貪婪模式:在整個表達式匹配成功的前提下,盡可能少的匹配 ( ? );
  • Python裏數量詞默認是貪婪的。

例1 : 源字符串:abbbc

使用貪婪的數量詞的正則表達式 ab* ,匹配結果: abbb。
* 決定了盡可能多匹配 b,所以a後面所有的 b 都出現了。

使用非貪婪的數量詞的正則表達式ab*?,匹配結果: a。
即使前面有 *,但是 ? 決定了盡可能少匹配 b,所以沒有 b。

例2: 源字符串:aa<div>test1</div>bb<div>test2</div>cc

使用貪婪的數量詞的正則表達式:<div>.*</div>

匹配結果:<div>test1</div>bb<div>test2</div>

這裏采用的是貪婪模式。在匹配到第一個“</div>”時已經可以使整個表達式匹配成功,但是由於采用的是貪婪模式,所以仍然要向右嘗試匹配,查看是否還有更長的可以成功匹配的子串。匹配到第二個“</div>”後,向右再沒有可以成功匹配的子串,匹配結束,匹配結果為“<div>test1</div>bb<div>test2</div>”

4、正則表達式測試網址

  

Python爬蟲開發【第1篇】【正則表達式】