Python爬虫入门七正则表达式
已經搞定了怎樣獲取頁面的內容,不過還差一步,這么多雜亂的代碼夾雜文字我們怎樣把它提取出來整理呢?下面就開始介紹一個十分強大的工具,正則表達式
1.了解正則表達式
正則表達式是用來匹配字符串非常強大的工具,在其他編程語言中同樣有正則表達式的概念,Python 同樣不例外。正則表達式的大致匹配過程是:
- 依次拿出表達式和文本中的字符比較,
- 如果每一個字符都能匹配,則匹配成功;一旦有匹配不成功的字符則匹配失敗。
- 如果表達式中有量詞或邊界,這個過程會稍微有一些不同。
2.正則表達式的語法規則
下面是 Python 中正則表達式的一些匹配規則
3.正則表達式相關注釋
(1)數量詞的貪婪模式和非貪婪模式
正則表達式通常用于在文本中查找匹配的字符串。Python 里數量詞默認是貪婪的(在少數語言里也可能是默認非貪婪),總是嘗試匹配盡可能多的字符;非貪婪的則相反,總是嘗試匹配盡可能少的字符。例如:正則表達式”ab“如果用于查找” abbbc”,將找到”abbb”。而如果使用非貪婪的數量詞”ab?”,將找到”a”。 注:我們一般使用非貪婪模式來提取。
(2)反斜杠問題
與大多數編程語言相同,正則表達式里使用”\“作為轉義字符,這就可能造成反斜杠困擾。假如你需要匹配文本中的字符”\“,那么使用編程語言表示的正則表達式里將需要 4 個反斜杠”\\“:前兩個和后兩個分別用于在編程語言里轉義成反斜杠,轉換成兩個反斜杠后再在正則表達式里轉義成一個反斜杠。 Python 里的原生字符串很好地解決了這個問題,這個例子中的正則表達式可以使用 r”\“表示。同樣,匹配一個數字的”\d” 可以寫成 r”\d”。有了原生字符串,不用擔心是不是漏寫了反斜杠,寫出來的表達式也更直觀
4.Python Re模塊
Python 自帶了 re 模塊,它提供了對正則表達式的支持。主要用到的方法列舉如下
#返回pattern對象 re.compile(string[,flag]) #以下為匹配所用函數 re.match(pattern, string[, flags]) re.search(pattern, string[, flags]) re.split(pattern, string[, maxsplit]) re.findall(pattern, string[, flags]) re.finditer(pattern, string[, flags]) re.sub(pattern, repl, string[, count]) re.subn(pattern, repl, string[, count])在介紹這幾個方法之前,我們先來介紹一下 pattern 的概念,pattern 可以理解為一個匹配模式,那么我們怎么獲得這個匹配模式呢?很簡單,我們需要利用 re.compile 方法就可以。例如
pattern = re.compile(r'hello')在參數中我們傳入了原生字符串對象,通過 compile 方法編譯生成一個 pattern 對象,然后我們利用這個對象來進行進一步的匹配。 另外大家可能注意到了另一個參數 flags,在這里解釋一下這個參數的含義: 參數 flag 是匹配模式,取值可以使用按位或運算符’|’表示同時生效,比如 re.I | re.M。 可選值有:
- re.I(全拼:IGNORECASE): 忽略大小寫(括號內是完整寫法,下同)
- re.M(全拼:MULTILINE): 多行模式,改變’^‘和’$'的行為(參見上圖)
- re.S(全拼:DOTALL): 點任意匹配模式,改變’.'的行為
- re.L(全拼:LOCALE): 使預定字符類 \w \W \b \B \s \S 取決于當前區域設定
- re.U(全拼:UNICODE): 使預定字符類 \w \W \b \B \s \S \d \D 取決于unicode定義的字符屬性
- re.X(全拼:VERBOSE): 詳細模式。這個模式下正則表達式可以是多行,忽略空白字符,并可以加入注釋。
以下七個方法中的 flags 同樣是代表匹配模式的意思,如果在 pattern 生成時已經指明了 flags,那么在下面的方法中就不需要傳入這個參數了。
(1)re.match(pattern, string[, flags])
這個方法將會從 string(我們要匹配的字符串)的開頭開始,嘗試匹配 pattern,一直向后匹配,如果遇到無法匹配的字符,立即返回 None,如果匹配未結束已經到達 string 的末尾,也會返回 None。兩個結果均表示匹配失敗,否則匹配 pattern 成功,同時匹配終止,不再對 string 向后匹配。下面我們通過一個例子理解一下
#導入re模塊 import re# 將正則表達式編譯成Pattern對象,注意hello前面的r的意思是“原生字符串” pattern = re.compile(r'hello')# 使用re.match匹配文本,獲得匹配結果,無法匹配時將返回None result1 = re.match(pattern,'hello') result2 = re.match(pattern,'helloo CQC!') result3 = re.match(pattern,'helo CQC!') result4 = re.match(pattern,'hello CQC!')#如果1匹配成功 if result1:# 使用Match獲得分組信息print result1.group() else:print '1匹配失敗!' #如果2匹配成功 if result2:# 使用Match獲得分組信息print result2.group() else:print '2匹配失敗!' #如果3匹配成功 if result3:# 使用Match獲得分組信息print result3.group() else:print '3匹配失敗!' #如果4匹配成功 if result4:# 使用Match獲得分組信息print result4.group() else:print '4匹配失敗!'輸出:
hello hello 3匹配失敗! hello匹配分析
我們還看到最后打印出了 result.group (),這個是什么意思呢?下面我們說一下關于 match 對象的的屬性和方法 Match 對象是一次匹配的結果,包含了很多關于此次匹配的信息,可以使用 Match 提供的可讀屬性或方法來獲取這些信息。
屬性:
方法:
(2)re.search(pattern, string[, flags])
search 方法與 match 方法極其類似,區別在于 match () 函數只檢測 re 是不是在 string 的開始位置匹配,search () 會掃描整個 string 查找匹配,match()只有在 0 位置匹配成功的話才有返回,如果不是開始位置匹配成功的話,match () 就返回 None。同樣,search 方法的返回對象同樣 match () 返回對象的方法和屬性。我們用一個例子感受一下
import re# 將正則表達式編譯成Pattern對象 pattern = re.compile(r'world') # 使用search()查找匹配的子串,不存在能匹配的子串時將返回None # 這個例子中使用match()無法成功匹配 match = re.search(pattern,'hello world!') if match:# 使用Match獲得分組信息print match.group() world(3)re.split(pattern, string[, maxsplit])
按照能夠匹配的子串將 string 分割后返回列表。maxsplit 用于指定最大分割次數,不指定將全部分割。我們通過下面的例子感受一下。
import repattern = re.compile(r'\d+') print re.split(pattern,'one1two2three3four4') ['one', 'two', 'three', 'four', ''](4)re.findall(pattern, string[, flags])
搜索 string,以列表形式返回全部能匹配的子串。我們通過這個例子來感受一下
import repattern = re.compile(r'\d+') print re.findall(pattern,'one1two2three3four4') ['1', '2', '3', '4'](5)re.finditer(pattern, string[, flags])
搜索 string,返回一個順序訪問每一個匹配結果(Match 對象)的迭代器。我們通過下面的例子來感受一下
import repattern = re.compile(r'\d+') for m in re.finditer(pattern,'one1two2three3four4'):print m.group(), 1 2 3 4(6)re.sub(pattern, repl, string[, count])
使用 repl 替換 string 中每一個匹配的子串后返回替換后的字符串。 當 repl 是一個字符串時,可以使用 \id 或 \g、\g 引用分組,但不能使用編號 0。 當 repl 是一個方法時,這個方法應當只接受一個參數(Match 對象),并返回一個字符串用于替換(返回的字符串中不能再引用分組)。 count 用于指定最多替換次數,不指定時全部替換。
import repattern = re.compile(r'(\w+) (\w+)') s = 'i say, hello world!'print re.sub(pattern,r'\2 \1', s) print re.sub(pattern,r'beijing', s) def func(m):return m.group(1).title() + ' ' + m.group(2).title()print re.sub(pattern,func, s) say i, world hello! beijing, beijing! I Say, Hello World!(7)re.subn(pattern, repl, string[, count])
返回元組(sub (repl, string [, count]), 替換次數)。
import repattern = re.compile(r'(\w+) (\w+)') s = 'i say, hello world!'print re.subn(pattern,r'\2 \1', s)def func(m):return m.group(1).title() + ' ' + m.group(2).title()print re.subn(pattern,func, s) ('say i, world hello!', 2) ('I Say, Hello World!', 2)5.Python Re 模塊的另一種使用方式
在上面我們介紹了 7 個工具方法,例如 match,search 等等,不過調用方式都是 re.match,re.search 的方式,其實還有另外一種調用方式,可以通過 pattern.match,pattern.search 調用,這樣調用便不用將 pattern 作為第一個參數傳入了,大家想怎樣調用皆可。 函數 API 列表
match(string[, pos[, endpos]]) | re.match(pattern, string[, flags]) search(string[, pos[, endpos]]) | re.search(pattern, string[, flags]) split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]) findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]) finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags]) sub(repl, string[, count]) | re.sub(pattern, repl, string[, count]) subn(repl, string[, count]) |re.sub(pattern, repl, string[, count])總結
以上是生活随笔為你收集整理的Python爬虫入门七正则表达式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Minecraft模组服开服
- 下一篇: windows隐藏python运行时的终