re模块的结果小练习题

时间:2022-04-29 20:32:30

1.匹配标签

 import re
ret = re.search('<(?P<tag_name>\w+)>\w+</(?P=tag_name)>','<h1>hello</h1>')
#还可以在分组中利用?P<name>的形式给分组起名字
#获取的匹配结果可以直接用group('名字')拿到对应的值
print(ret.group())
print(ret.group('tag_name')) # -------------------------
ret = re.search(r'<(\w+)>\w+</\1>','<h1>hello</h1>')
#如果不给分组起名字,也可以用\序号来找到对应的组,表说要找的内容和前面的组的内容一致
#获取的匹配结果可以直接用group(序号)拿到对应的值
print(ret.group())
print(ret.group(1))

匹配标签

2.匹配整数

 import re
ret = re.findall(r'\d+',"1-2*(60+(-40.35/5)-(-4*3))")
print(ret) import re
ret = re.findall(r'-?\d+\.\d*|(-?\d+)',"1-2*(60+(-40.35/5)-(-4*3))")
print(ret) ret.remove('')
print(ret)

数字匹配

3.数字匹配

 # 3.数字匹配
# 1.匹配一段文本中的每行的时间字符串,比如’1990-07-12‘ # 1.分别取出一年的十二个月:
while True:
cmd = input('请输入月份:>>')
if re.match(r'^(0?[1-9]|1[0-2])$',cmd):
print('格式正确')
else:
print('格式错误') # 2.
ret =re.match(r'^(0?[1-9]|1[0-2])$','')
print(ret.group()) # 一个月的31天
ret = re.match(r'^((0?[1-9])|((1|2)[0-9])|30|31)$','')#从头匹配
print(ret.group()) # 匹配QQ号
while True:
cmd = input('请输入你扣扣号:>>')
if re.match(r'^[1-9][0-9]{4,10}$',cmd):
print('输入正确')
else:
print('输入错误') # 浮点数
ret = re.match(r'-?\d+\.?\d*','21.5')
print(ret.group())

数字匹配

4.爬虫练习

 import requests

 import re
import json def getPage(url): response=requests.get(url)
return response.text def parsePage(s): com=re.compile('<div class="item">.*?<div class="pic">.*?<em .*?>(?P<id>\d+).*?<span class="title">(?P<title>.*?)</span>'
'.*?<span class="rating_num" .*?>(?P<rating_num>.*?)</span>.*?<span>(?P<comment_num>.*?)评价</span>',re.S) ret=com.finditer(s)
for i in ret:
yield {
"id":i.group("id"),
"title":i.group("title"),
"rating_num":i.group("rating_num"),
"comment_num":i.group("comment_num"),
} def main(num): url='https://movie.douban.com/top250?start=%s&filter='%num
response_html=getPage(url)
ret=parsePage(response_html)
print(ret)
f=open("move_info7","a",encoding="utf8") for obj in ret:
print(obj)
data=json.dumps(obj,ensure_ascii=False)
f.write(data+"\n") if __name__ == '__main__':
count=0
for i in range(10):
main(count)
count+=25