Home  >  Article  >  Backend Development  >  [Python] Web Crawler (7): Regular Expression Tutorial in Python

[Python] Web Crawler (7): Regular Expression Tutorial in Python

黄舟
黄舟Original
2017-01-21 14:28:381338browse

Next, I am going to use Abai to make a small example of a crawler.

But before that, let’s sort out the relevant content of regular expressions in Python in detail.

The role of regular expressions in the Python crawler is like the roster used by the teacher when taking roll calls. It is an indispensable magic weapon.

The following content is reproduced from CNBLOG: http://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html

I didn’t pay attention when editing, I’m really sorry.

1. Basics of regular expressions

1.1. Concept introduction

Regular expressions are a powerful tool for processing strings. It is not part of Python. .

The concept of regular expressions is also found in other programming languages. The only difference lies in the number of syntaxes supported by different programming languages.

It has its own unique syntax and an independent processing engine. In languages ​​that provide regular expressions, the syntax of regular expressions is the same.

The following figure shows the matching process using regular expressions:

[Python] Web Crawler (7): Regular Expression Tutorial in Python


The approximate matching process of regular expressions Yes:

1. Take out the expression and compare it with the characters in the text in turn,

2. If every character can be matched, the match is successful; once there is a character that fails to match, Match failed.

3. If there are quantifiers or boundaries in the expression, the process will be slightly different.

The following figure lists the regular expression metacharacters and syntax supported by Python:

[Python] Web Crawler (7): Regular Expression Tutorial in Python

##1.2. Greedy mode and non-greedy mode of quantifiers


Regular expressions are often used to find matching strings in text.

Greedy mode always tries to match as many characters as possible;

non-greedy mode is the opposite and always tries to match as few characters as possible.

Quantifiers in Python are greedy by default.


For example: if the regular expression "ab*" is used to find "abbbc", "abbb" will be found.

And if the non-greedy quantifier "ab*?" is used, "a" will be found.


1.3. Backslash problem


Same as most programming languages, "\" is used as an escape character in regular expressions , which may cause backslash confusion.

If you need to match the character "\" in the text, then 4 backslashes "\\\\" will be needed in the regular expression expressed in the programming language:

First The first and third are used to escape the second and fourth into backslashes in the programming language.

is converted into two backslashes\\ and then escaped in the regular expression. into a backslash to match the backslash\.

This is obviously very troublesome.


The native strings in Python solve this problem very well. The regular expression in this example can be represented by r"\\".

Similarly, "\\d" that matches a number can be written as r"\d".

With native strings, my mother no longer has to worry about my backslash problem~



2. Introducing the re module


2.1. Compile

Python provides support for regular expressions through the re module.

The general steps for using re are:

Step1: First compile the string form of the regular expression into a Pattern instance.

Step2: Then use the Pattern instance to process the text and obtain the matching result (a Match instance).

Step3: Finally, use the Match instance to obtain information and perform other operations.

Let’s create a new re01.py to test the application of re:

# -*- coding: utf-8 -*-  
#一个简单的re实例,匹配字符串中的hello字符串  
  
#导入re模块  
import re  
   
# 将正则表达式编译成Pattern对象,注意hello前面的r的意思是“原生字符串”  
pattern = re.compile(r'hello')  
   
# 使用Pattern匹配文本,获得匹配结果,无法匹配时将返回None  
match1 = pattern.match('hello world!')  
match2 = pattern.match('helloo world!')  
match3 = pattern.match('helllo world!')  
  
#如果match1匹配成功  
if match1:  
    # 使用Match获得分组信息  
    print match1.group()  
else:  
    print 'match1匹配失败!'  
  
  
#如果match2匹配成功  
if match2:  
    # 使用Match获得分组信息  
    print match2.group()  
else:  
    print 'match2匹配失败!'  
  
  
#如果match3匹配成功  
if match3:  
    # 使用Match获得分组信息  
    print match3.group()  
else:  
    print 'match3匹配失败!'

You can see that the console outputs three matching results:

[Python] Web Crawler (7): Regular Expression Tutorial in Python

Let’s take a closer look at the key methods in the code.


★ re.compile(strPattern[, flag]):


This method is the factory method of the Pattern class, used to compile regular expressions in string form is a Pattern object.

The second parameter flag is the matching mode. The value can use the bitwise OR operator '|' to indicate that it takes effect at the same time, such as re.I | re.M.

In addition, you can also specify the pattern in the regex string,

For example, re.compile('pattern', re.I | re.M) and re.compile('(? im)pattern') are equivalent.

Optional values ​​are:


  •     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): 详细模式。这个模式下正则表达式可以是多行,忽略空白字符,并可以加入注释。


以下两个正则表达式是等价的:

# -*- coding: utf-8 -*-  
#两个等价的re匹配,匹配一个小数  
import re  
  
a = re.compile(r"""\d +  # the integral part 
                   \.    # the decimal point 
                   \d *  # some fractional digits""", re.X)  
  
b = re.compile(r"\d+\.\d*")  
  
match11 = a.match('3.1415')  
match12 = a.match('33')  
match21 = b.match('3.1415')  
match22 = b.match('33')   
  
if match11:  
    # 使用Match获得分组信息  
    print match11.group()  
else:  
    print u'match11不是小数'  
      
if match12:  
    # 使用Match获得分组信息  
    print match12.group()  
else:  
    print u'match12不是小数'  
      
if match21:  
    # 使用Match获得分组信息  
    print match21.group()  
else:  
    print u'match21不是小数'  
  
if match22:  
    # 使用Match获得分组信息  
    print match22.group()  
else:  
    print u'match22不是小数'

re提供了众多模块方法用于完成正则表达式的功能。


这些方法可以使用Pattern实例的相应方法替代,唯一的好处是少写一行re.compile()代码,

但同时也无法复用编译后的Pattern对象。

这些方法将在Pattern类的实例方法部分一起介绍。

如一开始的hello实例可以简写为:

# -*- coding: utf-8 -*-  
#一个简单的re实例,匹配字符串中的hello字符串  
import re  
  
m = re.match(r'hello', 'hello world!')  
print m.group()

re模块还提供了一个方法escape(string),用于将string中的正则表达式元字符如*/+/?等之前加上转义符再返回


2.2. Match

Match对象是一次匹配的结果,包含了很多关于此次匹配的信息,可以使用Match提供的可读属性或方法来获取这些信息。

属性:

string: 匹配时使用的文本。

re: 匹配时使用的Pattern对象。

pos: 文本中正则表达式开始搜索的索引。值与Pattern.match()和Pattern.seach()方法的同名参数相同。

endpos: 文本中正则表达式结束搜索的索引。值与Pattern.match()和Pattern.seach()方法的同名参数相同。

lastindex: 最后一个被捕获的分组在文本中的索引。如果没有被捕获的分组,将为None。

lastgroup: 最后一个被捕获的分组的别名。如果这个分组没有别名或者没有被捕获的分组,将为None。

方法:

group([group1, …]):
获得一个或多个分组截获的字符串;指定多个参数时将以元组形式返回。group1可以使用编号也可以使用别名;编号0代表整个匹配的子串;不填写参数时,返回group(0);没有截获字符串的组返回None;截获了多次的组返回最后一次截获的子串。

groups([default]): 
以元组形式返回全部分组截获的字符串。相当于调用group(1,2,…last)。default表示没有截获字符串的组以这个值替代,默认为None。

groupdict([default]):
返回以有别名的组的别名为键、以该组截获的子串为值的字典,没有别名的组不包含在内。default含义同上。

start([group]): 
返回指定的组截获的子串在string中的起始索引(子串第一个字符的索引)。group默认值为0。

end([group]):
返回指定的组截获的子串在string中的结束索引(子串最后一个字符的索引+1)。group默认值为0。

span([group]):
返回(start(group), end(group))。

expand(template): 
将匹配到的分组代入template中然后返回。template中可以使用\id或\g、\g引用分组,但不能使用编号0。\id与\g是等价的;但\10将被认为是第10个分组,如果你想表达\1之后是字符'0',只能使用\g0。

下面来用一个py实例输出所有的内容加深理解:

# -*- coding: utf-8 -*-  
#一个简单的match实例  
  
import re  
# 匹配如下内容:单词+空格+单词+任意字符  
m = re.match(r&#39;(\w+) (\w+)(?P<sign>.*)&#39;, &#39;hello world!&#39;)  
  
print "m.string:", m.string  
print "m.re:", m.re  
print "m.pos:", m.pos  
print "m.endpos:", m.endpos  
print "m.lastindex:", m.lastindex  
print "m.lastgroup:", m.lastgroup  
  
print "m.group():", m.group()  
print "m.group(1,2):", m.group(1, 2)  
print "m.groups():", m.groups()  
print "m.groupdict():", m.groupdict()  
print "m.start(2):", m.start(2)  
print "m.end(2):", m.end(2)  
print "m.span(2):", m.span(2)  
print r"m.expand(r&#39;\g<2> \g<1>\g<3>&#39;):", m.expand(r&#39;\2 \1\3&#39;)  
   
### output ###  
# m.string: hello world!  
# m.re: <_sre.SRE_Pattern object at 0x016E1A38>  
# m.pos: 0  
# m.endpos: 12  
# m.lastindex: 3  
# m.lastgroup: sign  
# m.group(1,2): (&#39;hello&#39;, &#39;world&#39;)  
# m.groups(): (&#39;hello&#39;, &#39;world&#39;, &#39;!&#39;)  
# m.groupdict(): {&#39;sign&#39;: &#39;!&#39;}  
# m.start(2): 6  
# m.end(2): 11  
# m.span(2): (6, 11)  
# m.expand(r&#39;\2 \1\3&#39;): world hello!

2.3. Pattern

Pattern对象是一个编译好的正则表达式,通过Pattern提供的一系列方法可以对文本进行匹配查找。

Pattern不能直接实例化,必须使用re.compile()进行构造,也就是re.compile()返回的对象。

Pattern提供了几个可读属性用于获取表达式的相关信息:

pattern: 编译时用的表达式字符串。

flags: 编译时用的匹配模式。数字形式。

groups: 表达式中分组的数量。

groupindex: 以表达式中有别名的组的别名为键、以该组对应的编号为值的字典,没有别名的组不包含在内。

可以用下面这个例子查看pattern的属性:

# -*- coding: utf-8 -*-  
#一个简单的pattern实例  
  
import re  
p = re.compile(r&#39;(\w+) (\w+)(?P<sign>.*)&#39;, re.DOTALL)  
   
print "p.pattern:", p.pattern  
print "p.flags:", p.flags  
print "p.groups:", p.groups  
print "p.groupindex:", p.groupindex  
   
### output ###  
# p.pattern: (\w+) (\w+)(?P<sign>.*)  
# p.flags: 16  
# p.groups: 3  
# p.groupindex: {&#39;sign&#39;: 3}
下面重点介绍一下pattern的实例方法及其使用。
1.match
match(string[, pos[, endpos]]) | re.match(pattern, string[, flags]):
这个方法将从string的pos下标处起尝试匹配pattern;
如果pattern结束时仍可匹配,则返回一个Match对象;
如果匹配过程中pattern无法匹配,或者匹配未结束就已到达endpos,则返回None。
pos和endpos的默认值分别为0和len(string);
re.match()无法指定这两个参数,参数flags用于编译pattern时指定匹配模式。
注意:这个方法并不是完全匹配。
当pattern结束时若string还有剩余字符,仍然视为成功。
想要完全匹配,可以在表达式末尾加上边界匹配符&#39;$&#39;。
下面来看一个Match的简单案例:
# encoding: UTF-8  
import re  
   
# 将正则表达式编译成Pattern对象  
pattern = re.compile(r&#39;hello&#39;)  
   
# 使用Pattern匹配文本,获得匹配结果,无法匹配时将返回None  
match = pattern.match(&#39;hello world!&#39;)  
   
if match:  
    # 使用Match获得分组信息  
    print match.group()  
   
### 输出 ###  
# hello

2.search
search(string[, pos[, endpos]]) | re.search(pattern, string[, flags]): 
这个方法用于查找字符串中可以匹配成功的子串。

从string的pos下标处起尝试匹配pattern,

如果pattern结束时仍可匹配,则返回一个Match对象;

若无法匹配,则将pos加1后重新尝试匹配;

直到pos=endpos时仍无法匹配则返回None。

pos和endpos的默认值分别为0和len(string));

re.search()无法指定这两个参数,参数flags用于编译pattern时指定匹配模式。

那么它和match有什么区别呢?

match()函数只检测re是不是在string的开始位置匹配,

search()会扫描整个string查找匹配,


match()只有在0位置匹配成功的话才有返回,如果不是开始位置匹配成功的话,match()就返回none
例如:
print(re.match(‘super’, ‘superstition’).span())

会返回(0, 5)

print(re.match(‘super’, ‘insuperable’))

则返回None

search()会扫描整个字符串并返回第一个成功的匹配
例如:

print(re.search(‘super’, ‘superstition’).span())

返回(0, 5)
print(re.search(‘super’, ‘insuperable’).span())

返回(2, 7)

看一个search的实例:

# -*- coding: utf-8 -*-  
#一个简单的search实例  
  
import re  
   
# 将正则表达式编译成Pattern对象  
pattern = re.compile(r&#39;world&#39;)  
   
# 使用search()查找匹配的子串,不存在能匹配的子串时将返回None  
# 这个例子中使用match()无法成功匹配  
match = pattern.search(&#39;hello world!&#39;)  
   
if match:  
    # 使用Match获得分组信息  
    print match.group()  
   
### 输出 ###  
# world

3.split

split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]):
按照能够匹配的子串将string分割后返回列表。

maxsplit用于指定最大分割次数,不指定将全部分割。

import re  
   
p = re.compile(r&#39;\d+&#39;)  
print p.split(&#39;one1two2three3four4&#39;)  
   
### output ###  
# [&#39;one&#39;, &#39;two&#39;, &#39;three&#39;, &#39;four&#39;, &#39;&#39;]

4.findall

findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]):
搜索string,以列表形式返回全部能匹配的子串。

import re  
   
p = re.compile(r&#39;\d+&#39;)  
print p.findall(&#39;one1two2three3four4&#39;)  
   
### output ###  
# [&#39;1&#39;, &#39;2&#39;, &#39;3&#39;, &#39;4&#39;]

5.finditer

finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags]):
搜索string,返回一个顺序访问每一个匹配结果(Match对象)的迭代器。

import re  
   
p = re.compile(r&#39;\d+&#39;)  
for m in p.finditer(&#39;one1two2three3four4&#39;):  
    print m.group(),  
   
### output ###  
# 1 2 3 4

6.sub

sub(repl, string[, count]) | re.sub(pattern, repl, string[, count]):
使用repl替换string中每一个匹配的子串后返回替换后的字符串。 
当repl是一个字符串时,可以使用\id或\g、\g引用分组,但不能使用编号0。 
当repl是一个方法时,这个方法应当只接受一个参数(Match对象),并返回一个字符串用于替换(返回的字符串中不能再引用分组)。 
count用于指定最多替换次数,不指定时全部替换。

import re  
   
p = re.compile(r&#39;(\w+) (\w+)&#39;)  
s = &#39;i say, hello world!&#39;  
   
print p.sub(r&#39;\2 \1&#39;, s)  
   
def func(m):  
    return m.group(1).title() + &#39; &#39; + m.group(2).title()  
   
print p.sub(func, s)  
   
### output ###  
# say i, world hello!  
# I Say, Hello World!

7.subn

subn(repl, string[, count]) |re.sub(pattern, repl, string[, count]):
返回 (sub(repl, string[, count]), 替换次数)。

import re  
   
p = re.compile(r&#39;(\w+) (\w+)&#39;)  
s = &#39;i say, hello world!&#39;  
   
print p.subn(r&#39;\2 \1&#39;, s)  
   
def func(m):  
    return m.group(1).title() + &#39; &#39; + m.group(2).title()  
   
print p.subn(func, s)  
   
### output ###  
# (&#39;say i, world hello!&#39;, 2)  
# (&#39;I Say, Hello World!&#39;, 2)

至此,Python的正则表达式基本介绍就算是完成了^_^


以上就是[Python]网络爬虫(七):Python中的正则表达式教程的内容,更多相关内容请关注PHP中文网(www.php.cn)!



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn