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

新手上路,请多包涵

我有一个用户输入的字符串,我想搜索它并用我的替换字符串替换所有出现的单词列表。

 import re

prohibitedWords = ["MVGame","Kappa","DatSheffy","DansGame","BrainSlug","SwiftRage","Kreygasm","ArsonNoSexy","GingerPower","Poooound","TooSpicy"]

# word[1] contains the user entered message
themessage = str(word[1])
# would like to implement a foreach loop here but not sure how to do it in python
for themessage in prohibitedwords:
    themessage =  re.sub(prohibitedWords, "(I'm an idiot)", themessage)

print themessage

上面的代码不起作用,我确定我不明白 python for 循环是如何工作的。

原文由 Zac 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 377
2 个回答

您可以通过一次调用 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("<replaced>", 'this message contains Some really Random Words')
>>> the_message
'this message contains <replaced> really <replaced> <replaced>'

请注意,使用 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 指出的那样,如果你想替换 单词 而不是每个子字符串,你可以将单词边界添加到正则表达式中:

 big_regex = re.compile(r'\b%s\b' % r'\b|\b'.join(map(re.escape, words)))

这将替换 'random' 中的 'random words' 但不是 'pseudorandom words' 中的。

原文由 Bakuriu 发布,翻译遵循 CC BY-SA 3.0 许可协议

尝试这个:

 prohibitedWords = ["MVGame","Kappa","DatSheffy","DansGame","BrainSlug","SwiftRage","Kreygasm","ArsonNoSexy","GingerPower","Poooound","TooSpicy"]

themessage = str(word[1])
for word in prohibitedwords:
    themessage =  themessage.replace(word, "(I'm an idiot)")

print themessage

原文由 Artsiom Rudzenka 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题