python查找并修改文件中的内容_如何在Python中搜索和替换文本?

问题

您要搜索并替换字符串中的文本模式。

如果我们有一个非常简单的文字模式,则使用str.replace()方法是一个最佳解决方案。

示例def sample():

yield 'Is'

yield 'USA'

yield 'Colder'

yield 'Than'

yield 'Canada?'

text = ' '.join(sample())

print(f"Output \n {text}")

输出结果Is USA Colder Than Canada?

首先让我们看看如何搜索文本。# search for exact text

print(f"Output \n {text == 'USA'}")

输出结果False

我们可以使用基本的字符串方法搜索文本,例如str.find(),str.endswith(),str.startswith()。# text start with

print(f"Output \n {text.startswith('Is')}")

输出结果True# text ends with

print(f"Output \n {text.startswith('Is')}")

输出结果True# search text with find

print(f"Output \n {text.find('USA')}")

输出结果3

如果要搜索的输入文本更加复杂,则可以使用正则表达式和re模块。# Let us create a date in string format

date1 = '22/10/2020'# Let us check if the text has more than 1 digit.

# \d+ - match one or more digits

import re

if re.match(r'\d+/\d+/\d+', date1):

print('yes')

else:

print('no')

yes

现在,回到替换文本。如果要替换的文本和字符串很简单,则使用str.replace()。

输出结果print(f"Output \n {text.replace('USA', 'Australia')}")

输出结果Is Australia Colder Than Canada?

如果有复杂的模式需要搜索和替换,那么我们可以sub()在re模块中利用这些方法。

第一个参数sub()是要匹配的模式,第二个参数是替换模式。

在以下示例中,我们将以dd / mm / yyyy找到日期字段,并以yyyy-dd-mm格式替换它们。反斜杠数字(例如\ 3)表示模式中的捕获组号import re

sentence = 'Date is 22/11/2020. Tommorow is 23/11/2020.'

# sentence

replaced_text = re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', sentence)

print(f"Output \n {replaced_text}")

输出结果Date is 2020-22-11. Tommorow is 2020-23-11.

另一种方法是先编译表达式以获得更好的性能。

输出结果pattern = re.compile(r'(\d+)/(\d+)/(\d+)')

replaced_pattern = pattern.sub(r'\3-\1-\2', sentence)

print(f"Output \n {replaced_pattern}")

输出结果Date is 2020-22-11. Tommorow is 2020-23-11.

re.subn()将为我们提供替换文本的替换次数。

输出结果output, count = pattern.subn(r'\3-\1-\2', sentence)

print(f"Output \n {output}")

输出结果Date is 2020-22-11. Tommorow is 2020-23-11.

输出结果print(f"Output \n {count}")

输出结果2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值