零基础写python爬虫之神器正则表达式
接下来准备用糗百做一个爬虫的小例子。 一、 正则表达式基础 正则表达式是用于处理字符串的强大工具,它并不是Python的一部分。 正则表达式的大致匹配过程是: 下图列出了Python支持的正则表达式元字符和语法: 1.2. 数量词的贪婪模式与非贪婪模式 正则表达式通常用于在文本中查找匹配的字符串。 1.3. 反斜杠的问题 与大多数编程语言相同,正则表达式里使用""作为转义字符,这就可能造成反斜杠困扰。 二、 介绍re模块 2.1. Compile Python通过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匹配失败!' 可以看到控制台输出了匹配的三个结果: 下面来具体看看代码中的关键方法。 以下两个正则表达式是等价的: 复制代码 代码如下: # -*- 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提供了众多模块方法用于完成正则表达式的功能。 复制代码 代码如下: # -*- 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提供的可读属性或方法来获取这些信息。 复制代码 代码如下: # -*- coding: utf-8 -*- #一个简单的match实例 import re # 匹配如下内容:单词+空格+单词+任意字符 m = re.match(r'(w+) (w+)(?P<sign>.*)','hello world!') 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'g<2> g<1>g<3>'):",m.expand(r'2 13') ### 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): ('hello','world') # m.groups(): ('hello','world','!') # m.groupdict(): {'sign': '!'} # m.start(2): 6 # m.end(2): 11 # m.span(2): (6,11) # m.expand(r'2 13'): world hello! 2.3. Pattern 复制代码 代码如下: # -*- coding: utf-8 -*- #一个简单的pattern实例 import re p = re.compile(r'(w+) (w+)(?P<sign>.*)',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: {'sign': 3} 下面重点介绍一下pattern的实例方法及其使用。 1.match match(string[,pos[,endpos]]) | re.match(pattern,string[,flags]): 复制代码 代码如下: # encoding: UTF-8 import re # 将正则表达式编译成Pattern对象 pattern = re.compile(r'hello') # 使用Pattern匹配文本,获得匹配结果,无法匹配时将返回None match = pattern.match('hello world!') if match: # 使用Match获得分组信息 print match.group() ### 输出 ### # hello 2.search search(string[,endpos]]) | re.search(pattern,flags]): match()只有在0位置匹配成功的话才有返回,如果不是开始位置匹配成功的话,match()就返回none search()会扫描整个字符串并返回第一个成功的匹配 复制代码 代码如下: # -*- coding: utf-8 -*- #一个简单的search实例 import re # 将正则表达式编译成Pattern对象 pattern = re.compile(r'world') # 使用search()查找匹配的子串,不存在能匹配的子串时将返回None # 这个例子中使用match()无法成功匹配 match = pattern.search('hello world!') if match: # 使用Match获得分组信息 print match.group() ### 输出 ### # world 3.split 复制代码 代码如下: import re p = re.compile(r'd+') print p.split('one1two2three3four4') ### output ### # ['one','two','three','four',''] 4.findall 复制代码 代码如下: import re p = re.compile(r'd+') print p.findall('one1two2three3four4') ### output ### # ['1','2','3','4'] 5.finditer 复制代码 代码如下: import re p = re.compile(r'd+') for m in p.finditer('one1two2three3four4'): print m.group(), ### output ### # 1 2 3 4 6.sub sub(repl,count]) | re.sub(pattern,repl,count]): 复制代码 代码如下: import re p = re.compile(r'(w+) (w+)') s = 'i say,hello world!' print p.sub(r'2 1',s) def func(m): return m.group(1).title() + ' ' + m.group(2).title() print p.sub(func,s) ### output ### # say i,world hello! # I Say,Hello World! 7.subn 复制代码 代码如下: import re p = re.compile(r'(w+) (w+)') s = 'i say,hello world!' print p.subn(r'2 1',s) def func(m): return m.group(1).title() + ' ' + m.group(2).title() print p.subn(func,s) ### output ### # ('say i,world hello!',2) # ('I Say,Hello World!',2) 以上就是python神器正则表达式的基本介绍了,非常简单实用吧,希望对大家有所帮助^_^ (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |