网络爬虫2021-11-12

import re

def start_line(mark):
print("…")

def case_match():
start_line(“match”)
result1 = re.match(‘www’,‘www.baidu.com’)
print(result1)
result2 = re.match(‘com’,‘www.baidu.com’)
print(result2)

def case_group():
start_line(“group”)
line=“Cats are smarter than dogs”
matchObj=re.search(r’(.) are (.?) .*’, line, re.M|re.I)

if matchObj:
    print(matchObj.group())
    print(matchObj.group(1))
    print(matchObj.group(2))
    print(matchObj.group())
else:
    print("No match!")

def case_search():
start_line(“search”)
line=“Cats are smarter than dogs”
matchObj=re.search(r’(.) are (.?) .*’, line, re.M|re.I)

if matchObj:
    print(matchObj.group())
    print(matchObj.group(1))
    print(matchObj.group(2))
    print(matchObj.group())
else:
    print("No match!")

def case_match_search():
start_line(“match and search”)

line="Cats are smarter than dogs"

matchObj=re.match(r'dog', line, re.M | re.I)
if matchObj:
    print("match:",matchObj.group())
else:
    print("No match!")

searchObj=re.search(r'dogs',line, re.M | re.I)
if searchObj:
    print("search:",searchObj.group())
else:
    print("No match!")

def case_pattern():
start_line(“pattern”)
pattern=re.compile(r’([a-z]+)([a-z]+)’, re.I)

str="Hello World!I am OK."
result=pattern.match(str)
if result:
    print(result.group())
    print(result.group(1))
    print(result.group(2))
    print(result.group())
else:
    print("No match!")

def case_findall():
start_line(“findall”)

str='runoob 123 ggoole 123123123123 dsaf 321321321321'

result1=re.findall(r'\d+',str)
print(result1)

pattern= re.compile(r'\d+')
result2=pattern.findall(str)
print(result2)

result3=pattern.findall(str, 0, 10)
print(result3)

def case_finditer():
start_line(“findaiter”)

str='runoob 123 ggoole 123123123123 dsaf 321321321321'
result1=re.finditer(r'\d+', str)
print(result1)

for match in result1:
    print(match.group())

def case_sub():
start_line(“sub01”)

phone="157-0675-9966 # 这是一个电话号码"

#删除注释
num=re.sub(r'#.*$',"" ,phone)
print("电话号码(无注释):",num)

#删除非数字内容
num2=re.sub(r'\D',"",phone)
print("电话号码(全数字):",num2)

def case_split():
start_line(“split”)

line='I am your father.'

print(re.split(r'\W+', line))

print(re.split(r'(\W+)',line))

print(re.split(r'\W+',line, 1))

if name == ‘main’:
case_match()
case_group()
case_search()
case_match_search()
case_pattern()
case_findall()
case_finditer()
case_sub()
case_split()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值