9

ユーザーが文字列を入力しましたが、それを検索して、出現する単語のリストを置換文字列に置き換えたいと思います。

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ループがどのように機能するかを理解していないと確信しています。

4

3 に答える 3

33

あなたはへの単一の呼び出しでそれを行うことができます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'

于 2013-03-27T12:03:13.077 に答える
5

これを試して:

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
于 2013-03-27T12:00:03.463 に答える
0

コード:

prohibitedWords =["MVGame","Kappa","DatSheffy","DansGame",
                  "BrainSlug","SwiftRage","Kreygasm",
                  "ArsonNoSexy","GingerPower","Poooound","TooSpicy"]
themessage = 'Brain'   
self_criticism = '(I`m an idiot)'
final_message = [i.replace(themessage, self_criticism) for i in prohibitedWords]
print final_message

結果:

['MVGame', 'Kappa', 'DatSheffy', 'DansGame', '(I`m an idiot)Slug', 'SwiftRage',
'Kreygasm', 'ArsonNoSexy', 'GingerPower', 'Poooound','TooSpicy']
于 2013-03-27T12:45:30.563 に答える