第01阶段-基础入门-02-Python 爬虫基础-21节=====12.认识正则表达式

一.一个例子提取价格

 

import re

def re_demo():
    txt="If have purchasemore than 100 sets ,the price of product A is $9.90.";
    #解析数量和价格
    #\d  表示数字
    #+   表示匹配1-9数字
    # .  表示匹配所有字符
    # * 表示匹配0-多个字符
    # \$  反斜杠表示转义   $符号不变
    #\.? 表示匹配一个或者0个点
    #\d*   表示匹配一个或者多个数字
    m=re.search(r'(\d+).*\$(\d+\.?\d*)',txt)
    print(m.groups())

if __name__=="__main__":
    re_demo();

 

 

 

 

 

二.re模块介绍

1.search()与mach()的区别

print(re.search("c",txt)) #搜索匹配的字符串
    print(re.match("c",txt))   #从字符串开始开始匹配
    print(re.match(".*c",txt)) #c字符前面有一个或者多个字符

结果

<_sre.SRE_Match object; span=(2, 3), match='c'>    查询成功
None  失败
<_sre.SRE_Match object; span=(0, 3), match='abc'>    查询成功

2.split()

def c():
    txt="this is people";
    print(re.split(r'\W',txt))   #\W  表示用非字符分割字符串

    txt = "this & is || people";
    print(re.split(r'\W', txt))  # \W  表示用非字符分割字符串

结果

['this', 'is', 'people']
['this', '', '', 'is', '', '', '', 'people']    分割出文本,费字符没有啦

3.findall()

def c():
    txt="this is people";
    print(re.findall(r'\w+',txt))   #\w  表示用非字符分割字符串

    txt = "If have purchase more than 100 sets ,the price of product A is $9.90";
    print(re.findall(r'\d+\.?\d+', txt))  # \d+\.?\d+ 表示匹配xxxx.xxx
c()

结果

['this', 'is', 'people']
['100', '9.90']

4.finditer()

def c():
    txt = "If have purchase more than 100 sets ,the price of product A is $9.90";
    a=re.finditer(r"\d+\.?\d*",txt)
    for i in a:
        print(i.group())
c()

结果

100
9.90

5.sub (替换)

def c():
    txt = "If have purchase more than 100 sets ,the price of product A is $9.90";
    a=re.sub(r"\d+\.?\d*","999",txt)
    print(a)

c()

结果

If have purchase more than 999 sets ,the price of product A is $999


 

 

 

 

 

 

 

 

 

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞飞翼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值