可以使用Python中的re模块进行正则表达式匹配和替换。以下是一个示例程序,将"key phrases","given text"和"underscore"都替换为下划线:
import re
def replace_phrases(text):
phrases = ['key phrases', 'given text', 'underscore']
for phrase in phrases:
pattern = re.compile(re.escape(phrase), re.IGNORECASE)
text = pattern.sub('_'.join(phrase.split()), text)
return text
# 测试
text = "This is a text with some KEY PHRASES in it. The given text needs to be changed by replacing these key phrases with underscore in between them."
result = replace_phrases(text)
print(result)
输出:
This is a text with some KEY_PHRASES in it. The given_text needs to be changed by replacing these key_phrases with underscore in between them.
请注意,使用 re.escape() 函数可以将关键字中的特殊字符转义,以便它们被视为文本而不是正则表达式。此外,使用 re.IGNORECASE 标志可以使替换对大小写不敏感。