python 字符串替换单词_用python中的另一个字符串替换单词列表中的所有单词

您只需调用sub即可完成此操作:big_regex = re.compile('|'.join(map(re.escape, prohibitedWords)))

the_message = big_regex.sub("repl-string", str(word[1]))

示例:>>> import re

>>> prohibitedWords = ['Some', 'Random', 'Words']

>>> big_regex = re.compile('|'.join(map(re.escape, prohibitedWords)))

>>> the_message = big_regex.sub("", 'this message contains Some really Random Words')

>>> the_message

'this message contains really '

请注意,使用str.replace可能会导致细微的错误:>>> words = ['random', 'words']

>>> text = 'a sample message with random words'

>>> for word in words:

... text = text.replace(word, 'swords')

...

>>> text

'a sample message with sswords swords'

使用re.sub时会给出正确的结果:>>> big_regex = re.compile('|'.join(map(re.escape, words)))

>>> big_regex.sub("swords", 'a sample message with random words')

'a sample message with swords swords'

正如thg435所指出的,如果要替换单词而不是每个子字符串,则可以将单词边界添加到regex中:big_regex = re.compile(r'\b%s\b' % r'\b|\b'.join(map(re.escape, words)))

这将取代'random words'中的'random',而不是'pseudorandom words'。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值