re模块 常用函数

时间:2023-01-25 22:33:23

1. findall() 函数 

1 find('正则表达式',‘待匹配的字符串’)  #返回匹配到字符串,并存放在列表中

  详解见:https://www.cnblogs.com/nbk-zyc/p/11113328.html

re模块 常用函数re模块 常用函数
1 import re
2 
3 ret = re.findall('www.(baidu|oldboy).com', 'www.oldboy.com')
4 print(ret)  # ['oldboy']     这是因为findall会优先把匹配结果组里内容返回,如果想要匹配结果,取消权限即可
5 
6 ret = re.findall('www.(?:baidu|oldboy).com', 'www.oldboy.com')
7 print(ret)  # ['www.oldboy.com']
练习 findall() 与分组

2. search() 函数

1 import re
2 ret = re.search('abc', 'this is abcABC').group()
3 print(ret) #结果 : 'abc'
4 # 函数会在字符串内按规则匹配,当找到第一个匹配结果时就结束查找,然后返回一个包含匹配信息的对象,该对象可以 通过   调用group()方法   得到匹配的字符串, 
5 # 如果没有匹配到字符串,则返回None
1 obj = re.compile('\d{3}')  #将正则表达式编译成为一个 正则表达式对象,规则要匹配的是3个数字
2 ret = obj.search('abc123eeee') #正则表达式对象调用search,参数为待匹配的字符串
3 print(ret.group())  #结果 : 123

3. match() 函数

1 import re
2 ret = re.match('this', 'this is abcABC').group()
3 print(ret) #结果 : 'this'
4 # 在字符串开始处 就按规则匹配,其它 与search()函数使用方法一样

4 finditer() 函数

1 import re
2 ret = re.finditer('\d', 'ds3sy4784a')   #finditer返回一个存放匹配结果的迭代器
3 print(ret)  # <callable_iterator object at 0x10195f940>
4 print(next(ret).group())  #查看第一个结果  '3'
5 print(next(ret).group())  #查看第二个结果  '4'
6 print([i.group() for i in ret])  #查看剩余的匹配结果 ['7', '8', '4']

5 sub() 和 subn() 函数

1 import re
2 ret = re.sub('\d', 'H', 'eva3egon4yuan4', 1)#将数字替换成'H',参数1表示只替换1个
3 print(ret) #evaHegon4yuan4
4 
5 ret = re.subn('\d', 'H', 'eva3egon4yuan4')
6 print(ret)
7 #将数字替换成'H',返回元组(替换的结果,替换了多少次),即('evaHegonHyuanH', 3)

6 split() 函数

1 ret = re.split('[ab]', 'abcd')  # 先按'a'分割得到''和'bcd',在对''和'bcd'分别按'b'分割
2 print(ret)  # ['', '', 'cd']
re模块 常用函数re模块 常用函数
1 ret=re.split("\d+","eva3egon4yuan")
2 print(ret) #结果 : ['eva', 'egon', 'yuan']
3 
4 ret=re.split("(\d+)","eva3egon4yuan")
5 print(ret) #结果 : ['eva', '3', 'egon', '4', 'yuan']
6 
7 #在匹配部分加上()之后所切出的结果是不同的,
8 #没有()的没有保留所匹配的项,但是有()的却能够保留了匹配的项,
9 #这个在某些需要保留匹配部分的使用过程是非常重要的。
练习-split() 与分组

扩展练习

re模块 常用函数re模块 常用函数
 1 ret = re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>")
 2 #还可以在分组中利用 ?P<name>的形式给分组起名字
 3 #获取的匹配结果可以直接用group('名字')拿到对应的值
 4 print(ret.group('tag_name'))  #结果 :h1
 5 print(ret.group())  #结果 :<h1>hello</h1>
 6 
 7 ret = re.search(r"<(\w+)>\w+</\1>","<h1>hello</h1>")
 8 #如果不给组起名字,也可以用  \序号   来找到对应的组,表示要找的内容和前面的组内容一致
 9 #获取的匹配结果可以直接用group(序号)拿到对应的值
10 print(ret.group(1)) #结果 :h1
11 print(ret.group())  #结果 :<h1>hello</h1>
匹配标签
re模块 常用函数re模块 常用函数
 1 import re
 2 
 3 #匹配数字
 4 ret=re.findall(r"\d+","1-2*(60+(-40.35/5)-(-4*3))")
 5 print(ret) #['1', '2', '60', '40', '35', '5', '4', '3']
 6 
 7 #匹配整数
 8 ret=re.findall(r"-?\d+\.\d*|(-?\d+)","1-2*(60+(-40.35/5)-(-4*3))")
 9 print(ret) #['1', '-2', '60', '', '5', '-4', '3']
10 ret.remove("")
11 print(ret) #['1', '-2', '60', '5', '-4', '3']
12 
13 #匹配实数
14 ret=re.findall(r"-?\d+\.\d*|-?\d+","1-2*(60+(-40.35/5)-(-4*3))")
15 print(ret) #['1', '-2', '60', '-40.35', '5', '-4', '3']
匹配数字/整数/实数
re模块 常用函数re模块 常用函数
 1 import re
 2 from urllib.request import urlopen
 3 
 4 def getPage(url):
 5     response = urlopen(url)
 6     return response.read().decode('utf-8')
 7 
 8 def parsePage(s):
 9     ret = re.findall(
10         '<div class="item">.*?'
11         '<div class="pic">.*?'
12         '<em .*?>'
13         '(?P<id>\d+).*?'
14         '<span class="title">(?P<title>.*?)</span>.*?'
15         '<span class="rating_num" .*?>(?P<rating_num>.*?)</span>.*?'
16         '<span>(?P<comment_num>.*?)评价</span>',s,re.S)
17     return ret
18 
19 def main(num):
20     url = 'https://movie.douban.com/top250?start=%s&filter=' % num    # %s标记每页的首条信息
21     response_html = getPage(url)    #获取网页的全部内容
22     ret = parsePage(response_html) #解析所需求的信息
23     print(ret)
24 
25 count = 0
26 for i in range(10):   # 10页
27     main(count)
28     count += 25        # 每页25条信息
爬取网页-简单版
re模块 常用函数re模块 常用函数
 1 from urllib.request import urlopen
 2 import re
 3 import json
 4 
 5 def getPage(url):
 6     response = urlopen(url)
 7     return response.read().decode('utf-8')
 8 def parsePage(s):
 9     com = re.compile(
10         '<div class="item">.*?'
11         '<div class="pic">.*?'
12         '<em .*?>'
13         '(?P<id>\d+).*?'
14         '<span class="title">(?P<title>.*?)</span>.*?'
15         '<span class="rating_num" .*?>(?P<rating_num>.*?)</span>.*?'
16         '<span>(?P<comment_num>.*?)评价</span>', re.S)
17     ret = com.finditer(s)   # finditer返回一个存放匹配结果的迭代器
18     for i in ret:
19         yield {
20             "id": i.group("id"),
21             "title": i.group("title"),
22             "rating_num": i.group("rating_num"),
23             "comment_num": i.group("comment_num"),
24         }
25 def main(num):
26     url = 'https://movie.douban.com/top250?start=%s&filter=' % num
27     response_html = getPage(url)
28     ret = parsePage(response_html)
29     #print(ret)
30 
31     f = open("move_info7", "a", encoding="utf-8")
32     for obj in ret:
33         print(obj)
34         data = json.dumps(obj, ensure_ascii=False)
35         f.write(data + "\n")
36     f.close()
37 
38 if __name__ == '__main__':
39     count = 0
40     for i in range(10):
41         main(count)
42         count += 25
爬取网页-完整版