用正则表达式提取数据
正则表达式,又称规则表达式,通常被用来检索、替换那些符合某个模式(规则)的文本。
单字符匹配,多字符匹配,匹配分组,(三大类)
对文本进行匹配查找的一系列方法
😃 match 方法:从起始位置开始查找,一次匹配
😃 search 方法:从任何位置开始查找,一次匹配
😃 findall 方法:全部匹配,返回列表
😃 finditer 方法:全部匹配,返回迭代器
😃 split 方法:分割字符串,返回列表
😃 sub 方法:替换
这些方法要牢记哦!
数据提取中常用的操作
1.抓取标签间的内容
案例:抓取 title 标签间的内容
from urllib import request
import re
import chardet
def down(url):
head = {}
#写入 User Agent 信息
head['User-Agent'] = 'Mozilla/5.0 (Linux; Android 4.1.1; Nexus 7 Build/JRO03D)
AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Safari/535.19'
#创建 Request 对象
req = request.Request(url, headers=head)
response = request.urlopen(req)
html = response.read()
charset = chardet.detect(html)
#print(charset)
#print(charset['encoding'])
html = html.decode(charset['encoding'])
return html
if __name__ == "__main__":
#print('hello')
html = down("https://fanyi.baidu.com/")
pat = r'<title>(.*?)</title>'
ex = re.compile(pat, re.M|re.S) #只取中间的文字
obj = re.search(ex, html)
title = obj.group(1)
print(title)
案例:抓取超链接标签间的内容
from urllib import request
import re
import chardet
def down(url):
head = {}
#写入 User Agent 信息
head['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
#创建 Request 对象
req = request.Request(url, headers=head)
response = request.urlopen(req)
html = response.read()
charset = chardet.detect(html)
#print(charset)
print(charset['encoding'])
html = html.decode(charset['encoding'])
return html
if __name__ == "__main__":
# 获取超链接<a>和</a>之间内容
url = "https://www.baidu.com/"
html = down(url)
print(html)
pat = re.compile(r'<a .*?>(.*?)</a>',re.M|re.S)
texts = pat.findall(html)
for t in texts:
print(t)
案例:抓取 tr\td 标签间的内容
if __name__ == "__main__":
content = '''
<html>
<head><title>表格</title></head>
<body>
<table border=1>
<tr><th>学号</th><th>姓名</th></tr>
<tr><td>1001</td><td>李白</td></tr>
<tr><td>1002</td><td>杜甫</td></tr>
</table>
</body>
</html>
'''
# 获取<tr></tr>间内容
res = r'<tr>(.*?)</tr>'
texts = re.findall(res, content, re.S | re.M)
for m in texts:
print(m)
# 获取<th></th>间内容
for m in texts:
res_th = r'<th>(.*?)</th>'
m_th = re.findall(res_th, m, re.S | re.M)
for t in m_th:
print(t)
# 直接获取<td></td>间内容
res = r'<td>(.*?)</td><td>(.*?)</td>'
texts = re.findall(res, content, re.S | re.M)
for m in texts:
print(m[0], m[1])
2.抓取标签中的参数
案例:抓取超链接标签的 URL
import re
content = '''
<a href="http://news.baidu.com" name="tj_trnews" class="mnav">新闻</a>
<a href="http://www.hao123.com" name="tj_trhao123" class="mnav">hao123</a>
<a href="http://map.baidu.com" name="tj_trmap" class="mnav">地图</a>
<a href="http://v.baidu.com" name="tj_trvideo" class="mnav">视频</a>
'''
res = r'href="(.+?)"'
urls = re.findall(res, content, re.I | re.S | re.M)
for url in urls:
print(url)
案例:抓取图片超链接标签的 URL
import re
content = '''<img alt="Python" src="http://www..youkuaiyun.com/eastmount.jpg" />'''
urls = re.findall('src="(.*?)"', content, re.I|re.S|re.M)
print(urls)
案例:获取 URL 中最后一个参数
import re
content = '''<img alt="Python" src="http://www..youkuaiyun.com/eastmount.jpg" />'''
urls = 'http://www..youkuaiyun.com/eastmount.jpg'
name = urls.split('/')[-1]
print(name)
编译模式(选)
使用 compile() 函数将正则表达式的字符串形式编译为一个 Pattern 对象,然后调用正则
表达式对象的相应方法。
推荐使用编译模式,正则对象可以多次使用,可以大大地提高搜索的效率
compile 函数
compile 函数用于编译正则表达式,生成一个 Pattern 对象
import re
# 将正则表达式编译成 Pattern 对象
pattern = re.compile(r'\d+')
Pattern 对象
提供了对文本进行匹配查找的一系列方法
▶ match 方法:从起始位置开始查找,一次匹配
▶ search 方法:从任何位置开始查找,一次匹配
▶ findall 方法:全部匹配,返回列表
▶ finditer 方法:全部匹配,返回迭代器
▶ split 方法:分割字符串,返回列表
▶ sub 方法:替换
以下是对各种方法的使用讲解!!!
match 方法
从字符串的头部戒者指定位置开始查找一次匹配,只要找到了一个匹配的结果就返回
match(string[, pos[, endpos]])
string 是待匹配的字符串
pos 和 endpos 可选参数,指定字符串的起始和终点位置,默认值分别是 0 和 len
(字符串长度)。
当匹配成功时,返回一个 Match 对象,如果没有匹配上,则返回 None。
import re
pattern = re.compile(r'\d+') # 用于匹配至少一个数字
m = pattern.match('one12twothree34four') # 查找头部,没有匹配
print(m)
m = pattern.match('one12twothree34four', 2, 10) # 从'e'的位置开始匹配,没有匹配
print(m)
m = pattern.match('one12twothree34four', 3, 10) # 从'1'的位置开始匹配,正好匹配
print(m) # 返回一个 Match 对象
print(m.group(0)) # 可省略 0
print(m.start(0)) # 可省略 0
print(m.end(0)) # 可省略 0
print(m.span(0)) # 可省略 0
Match 对象
group([group1, …])获得一个戒多个分组匹配的字符串
group() 戒 group(0) 获得整个匹配的子串
start([group]) 获取分组匹配的子串在整个字符串中的起始位置(子串第一个字符的索引)
end([group]) /获取分组匹配的子串在整个字符串中的结束位置(子串最后一个字符的索引+1)
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 对象
print(m.group(0)) # 返回匹配成功的整个子串
print(m.span(0)) # 返回匹配成功的整个子串的索引
print(m.group(1)) # 返回第一个分组匹配成功的子串
print(m.span(1)) # 返回第一个分组匹配成功的子串的索引
print(m.group(2)) # 返回第二个分组匹配成功的子串
print(m.span(2)) # 返回第二个分组匹配成功的子串
print(m.groups()) # 等价于 (m.group(1), m.group(2), ...)
print(m.group(3)) # 不存在第三个分组 IndexError: no such group
search 方法
查找字符串的任何位置,只匹配一次,只要找到了一个匹配的结果就返回
search(string[, pos[, endpos]])
string 是待匹配的字符串
pos 和 endpos 可选参数,指定字符串的起始和终点位置
当匹配成功时,返回一个 Match 对象,如果没有匹配上,则返回 None。
import re
pattern = re.compile('\d+')
m = pattern.search('one12twothree34four') # 这里如果使用 match 方法则不匹配
print(m.group())
m = pattern.search('one12twothree34four', 10, 30) # 指定字符串区间
print(m.group())
print(m.span())
findall 方法
以列表形式返回全部能匹配的子串,如果没有匹配,则返回一个空列表。
findall(string[, pos[, endpos]])
string 待匹配的字符串
pos 和 endpos 可选参数,指定字符串的起始和终点位置。
范例
import re
pattern = re.compile(r'\d+') # 查找数字
result1 = pattern.findall('hello 123456 789')
result2 = pattern.findall('one1two2three3four4', 0, 10)
print(result1)
print(result2)
finditer 方法
搜索所有匹配的结果。返回一个迭代器,可顺序访问每一个匹配的结果(Match 对象)
范例
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()))
split 方法
按照能够匹配的子串将字符串分割后返回列表
split(string[, maxsplit])
maxsplit 用于指定最大分割次数,丌指定将全部分割。
范例
import re
p = re.compile(r'[\s,;]+')
print(p.split('a,b;; c d'))
sub 方法
方法用于替换。
sub(repl, string[, count])
epl 可以是字符串也可以是一个函数:
▶如果 repl 是字符串,则会使用 repl 去替换字符串每一个匹配的子串
▶ 如果 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) # 最多替换一次
贪婪模式与非贪婪模式 (重点!!!)
贪婪模式:在整个表达式匹配成功的前提下,尽可能多的匹配 ( * );
非贪婪模式:在整个表达式匹配成功的前提下,尽可能少的匹配 ( ? );
Python 里数量词默认是贪婪的。
示例一
import re
str = 'abbbc'
#贪婪模式
pattern = re.compile(r'ab*') # * 决定了尽可能多匹配 b,结果是 abbb
result = pattern.match(str)
print(result.group())
#非贪婪模式
pattern = re.compile(r'ab*?') # *? 决定了尽可能少匹配 b,结果是 a
result = pattern.match(str)
print(result.group())
pattern = re.compile(r'ab+?') # *? 决定了尽可能少匹配 b,结果是 ab
result = pattern.match(str)
print(result.group())
示例二
import re
#贪婪模式
str = "aa<div>test1</div>bb<div>test2</div>cc"
pattern = re.compile(r'<div>.*</div>') #*决定了尽可能多匹配 b, 结果是<div>test1</div>bb<div>test2</div>
result = pattern.search(str)
print(result.group())
#非贪婪模式
str = "aa<div>test1</div>bb<div>test2</div>cc"
pattern = re.compile(r'<div>.*?</div>') # *? 决定了尽可能少匹配 b,结果是<div>test1</div>
result = pattern.search(str)
print(result.group())
匹配中文
中文的 unicode 编码范围 主要在 [u4e00-u9fa5] (全角(中文)标点等除外),丌过,
在大部分情况下,应该是够用的。
假设现在想把字符串 title = u’你好,hello,世界’ 中的中文提取出来,可以这么做:
import re
title = '你好,hello,世界'
pattern = re.compile(r'[\u4e00-\u9fa5]+')
result = pattern.findall(title)
print(result)
再给大家安利一个好用的正则表达式测试网站 :
http://tool.oschina.net/regex/
文章纯属手打 给个赞哦!!!