2013-03-27 19 views
6

Ho una stringa immessa dall'utente e voglio cercarla e sostituire qualsiasi occorrenza di un elenco di parole con la mia stringa sostitutiva.Sostituisci tutte le parole dall'elenco delle parole con un'altra stringa in 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 

Il codice precedente non funziona, sono sicuro di non capire come funziona Python for loops.

+0

Si dovrebbe cercare di verificare l'attuazione SpamBayes per Python potrebbe essere più scalabile. – dusual

risposta

11

Potete farlo con una singola chiamata a sub:

big_regex = re.compile('|'.join(map(re.escape, prohibitedWords))) 
the_message = big_regex.sub("repl-string", str(word[1])) 

Esempio:

>>> 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>' 

noti che usare str.replace può portare a bug sottili :

>>> 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' 

durante l'utilizzo re.sub dà il risultato corretto:

>>> 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' 

Come thg435 sottolinea, se si desidera sostituire parole e non ogni sottostringa è possibile aggiungere i confini di parole per l'espressione regolare:

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

questo sostituirebbe 'random' in 'random words' ma non in 'pseudorandom words'.

+0

potete mostrare una corsa –

+0

Dovreste romperlo se aveste molte parole da sostituire, però. – DSM

+0

Si potrebbe voler racchiudere la propria espressione in '\ b' per evitare di sostituire" coda "in" rivenditori ". – georg

4

provare questo:

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 
+0

Questo è fragile: come ha spiegato Bakuriu, si rompe facilmente quando una delle parole proibite è una sottostringa di un'altra. – Adam

+0

@codesparkle non significa che è sbagliato, si sceglie sempre la vostra opzione dipende da determinate condizioni –

0

Codice:

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 

Risultato:

['MVGame', 'Kappa', 'DatSheffy', 'DansGame', '(I`m an idiot)Slug', 'SwiftRage', 
'Kreygasm', 'ArsonNoSexy', 'GingerPower', 'Poooound','TooSpicy'] 
Problemi correlati