如何在Python中搜索和替换文本?

如何在Python中搜索和替换文本?

阅读更多:Python 教程

问题

您想在字符串中搜索和替换文本模式。

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

例子

def sample():
yield 'Is'
yield 'USA'
yield 'Colder'
yield 'Than'
yield 'Canada?'

text = ' '.join(sample())
print(f"输出 \n {text}")

输出

Is USA Colder Than Canada?

让我们首先看一下如何搜索文本。

#搜索确切的文本
print(f"输出 \n {text == 'USA'}")

输出

False

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

#以文本开始
print(f"输出 \n {text.startswith('Is')}")

输出

True
#文本以结束
print(f"输出 \n {text.startswith('Is')}")

输出

True
#使用find搜索文本
print(f"输出 \n {text.find('USA')}")

输出

3

如果要搜索的输入文本更加复杂,那么我们可以使用正则表达式和re模块。

#让我们以字符串格式创建日期
date1 = '22/10/2020'
#让我们检查文本是否有多于1位数字。
#\d+ - 匹配一个或多个数字
import re
if re.match(r'\d+/\d+/\d+', date1):
print('yes')
else:
print('no')
yes

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

输出

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

输出

Is Australia Colder Than Canada?

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

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

在下面的示例中,我们将找到dd/mm/yyyy中的日期字段并将它们替换为格式- yyyy-dd-mm。反斜杠数字,如\ 3,是指模式中的捕获组编号。

import re
sentence = 'Date is 22/11/2020. Tommorow is 23/11/2020.'
#句子
replaced_text = re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', sentence)
print(f"输出 \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"输出 \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"输出 \n {output}")

输出

Date is 2020-22-11. Tommorow is 2020-23-11.

输出

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

输出

2

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程