Python正则表达式实战案例解析

1、对于给定的输入文件,打印出所有包含字符串“two”的行。

需要将 word = re.compile() 改为 word = re.compile(r'two') ,完整代码如下:

filename = 'programming_quotes.txt'
word = re.compile(r'two')
with open(filename, 'r') as ip_file:
    for ip_line in ip_file:
        if word.search(ip_line):
            print(ip_line, end='')

2、对于给定的输入字符串,打印所有不包含字符 2 的行。给定输入字符串如下: apple 24mango 50guava 42onion 31water 10

需要在 re.compile() 中填入 r'2' ,完整代码如下:

import re

purchases = 'apple 24mango 50guava 42onion 31water 10'
num = re.compile(r'2')

for line in purchases.split(): 
    if not num.search(line): 
        print(line)

运行上述代码后,输出结果为:

mango 50
onion 31
water 10

3、对于给定的URL,统计包含“is”或“the”作为完整单词的总行数。注意,for循环中的每一行都是字节数据类型。

import urllib.request
import re

scarlet_pimpernel_link = r'https://www.gutenberg.org/cache/epub/60/pg60.txt'
word_expr = re.compile(rb'\b(is|the)\b')
count = 0

with urllib.request.urlopen(scarlet_pimpernel_link) as ip_file:
    for line in ip_file:
        if word_expr.search(line):
            count += 1

print(count)

4、对于给定的输入字符串,仅将整个单词“red”替换为“brown”

可使用代码 re.sub(r'\bred\b', 'brown', 'bred red spread credible') 实现,输出为 'bred brown spread credible'

5、对于给定的输入列表,筛选出所有包含被单词字符包围的 42 的元素。

由于未给出输入列表,无法确定该答案是否正确,应输出 DELETE。

6、对于给定的输入字符串,仅当整个单词“mall”位于行首时,对其进行替换。

可使用正则表达式和 re.sub() 函数实现,参考代码如下:

print(re.sub(r'^mall', r'1234', para, flags=re.M))

其中 r'^mall' 匹配行首的 mall r'1234' 是替换内容, flags=re.M 表示多行模式。

7、对于给定的输入列表 [‘lovely’, ‘1 dentist’, ‘2 lonely’, ‘eden’, ‘fly away’, ‘dent’],过滤出所有以 den 开头或以 ly 结尾的元素。

[e for e in ['lovely', '1 dentist'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值