可以使用Python中的re模块来实现该功能。具体实现步骤如下:
定义一个函数,接受两个参数:文本和关键短语列表。
使用re模块中的sub()函数,replace参数的值为一个匹配模式,使用'|'操作符将关键短语列表拼接成一个匹配模式,将模式中匹配的字符串替换为空格。
返回结果字符串即可。
示例代码如下:
import re
def replace_phrases(text, phrases): pattern = '|'.join(phrases) result = re.sub(pattern, '_', text) return result
text = 'This is a text with some key phrases like this one, that one and the other one.' phrases = ['this one', 'that one', 'the other one']
new_text = replace_phrases(text, phrases) print(new_text) # 输出结果:This is a text with some key phrases like _, _ and .