如何在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