2013-03-27 89 views
6

Tôi có chuỗi người dùng đã nhập và tôi muốn tìm kiếm và thay thế bất kỳ lần xuất hiện nào của danh sách từ bằng chuỗi thay thế của tôi.Thay thế tất cả các từ trong danh sách từ bằng một chuỗi khác trong 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 

Mã trên không hoạt động, tôi chắc rằng tôi không hiểu cách thức hoạt động của vòng lặp.

+0

Bạn nên thử kiểm tra thực hiện SpamBayes cho python có thể được mở rộng hơn. – dusual

Trả lời

11

Bạn có thể làm điều đó với một cuộc gọi duy nhất để sub:

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

Ví dụ:

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

Lưu ý rằng việc sử dụng str.replace có thể dẫn đến lỗi vi tế :

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

khi sử dụng re.sub cho kết quả chính xác:

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

Như thg435 chỉ ra, nếu bạn muốn thay thế lời và không phải mọi substring bạn có thể thêm các ranh giới từ vào regex:

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

điều này sẽ thay thế 'random' trong 'random words' nhưng không phải trong 'pseudorandom words'.

+0

bạn có thể hiển thị chạy –

+0

Bạn sẽ phải chia nhỏ nếu bạn có nhiều từ để thay thế. – DSM

+0

Bạn có thể muốn kèm theo biểu thức của bạn trong '\ b' để tránh thay thế" đuôi "trong" nhà bán lẻ ". – georg

4

thử điều này:

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

Đây là giòn: như Bakuriu giải thích, nó dễ dàng phá vỡ khi một trong những từ bị cấm là một chuỗi con khác. – Adam

+0

@codesparkle nó không có nghĩa là sai, bạn luôn chọn tùy chọn của bạn phụ thuộc vào điều kiện nhất định –

0

Code:

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 

Kết quả:

['MVGame', 'Kappa', 'DatSheffy', 'DansGame', '(I`m an idiot)Slug', 'SwiftRage', 
'Kreygasm', 'ArsonNoSexy', 'GingerPower', 'Poooound','TooSpicy'] 
Các vấn đề liên quan