Zac*_*Zac 8 python text replace for-loop
我有一个用户输入的字符串,我想搜索它并用我的替换字符串替换任何出现的单词列表.
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
Run Code Online (Sandbox Code Playgroud)
上面的代码不起作用,我确定我不明白python for循环是如何工作的.
Bak*_*riu 25
你可以通过一次调用来做到这一点sub:
big_regex = re.compile('|'.join(map(re.escape, prohibitedWords)))
the_message = big_regex.sub("repl-string", str(word[1]))
Run Code Online (Sandbox Code Playgroud)
例:
>>> 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>'
Run Code Online (Sandbox Code Playgroud)
请注意,使用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'
Run Code Online (Sandbox Code Playgroud)
使用时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'
Run Code Online (Sandbox Code Playgroud)
正如thg435指出的那样,如果你想要替换单词而不是每个子字符串,你可以将单词边界添加到正则表达式:
big_regex = re.compile(r'\b%s\b' % r'\b|\b'.join(map(re.escape, words)))
Run Code Online (Sandbox Code Playgroud)
这将取代'random'中'random words'而不是在'pseudorandom words'.
尝试这个:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18473 次 |
| 最近记录: |