eshi
eshi

Reputation: 57

Python: Replacing foul words with characters from a sentence

I'm trying to replace all foul words in a sentence into random characters. I'm gonna use it for my project Mailing. So here's what I did so far.

curse=["apple","ball","car"]
fil = ["!","@","#","$","%","^","&","*","(",")"]
filword = ""
flag=0
word = raw_input(">>")
for each in curse:
    if each == word:
        worlen = len(word)
        flag=1
if flag==1:
    for c in fil:
        if len(filword) != worlen:
            filword+= c
word= word.replace(word, filword)
print word

assuming that those words from a list curse are foul words. I can already translate it to random characters. My problem is how can I replace foul words from sentence. Example:

>> Apple you, Ball that car

I want my output to be like this:

!@#$% you, !@#$ that !@#

How can I do that? Thanks! :)

Upvotes: 1

Views: 109

Answers (3)

idjaw
idjaw

Reputation: 26580

If you don't care about each character having its own unique filter replacement, you can use random.sample to choose any n items from your filter, where n will be the length of the word. So, with that in mind, you can do this:

from random import sample

curse=["apple","ball","car"]
fil = ["!","@","#","$","%","^","&","*","(",")"]
s = "this apple is awesome like a ball car man"
ns = []

for w in s.split():
    ns.append(''.join(sample(fil, len(w)))) if w in curse else ns.append(w)
print(' '.join(ns))
# this ()*!^ is awesome like a %$^& @$^ man

Upvotes: 0

Eugene Lisitsky
Eugene Lisitsky

Reputation: 12855

    import re
    word2 = re.sub(r'\w+', lambda x: x.group(0).lower() in curse and ''.join(fil[:len(c)]) or x.group(0), word)        
    print (word2)

    >>> '!@#$ you, !@#$ that !@#$'

Upvotes: 1

Priyansh Goel
Priyansh Goel

Reputation: 2660

curse=["apple","ball","car"]
fil = ["!","@","#","$","%","^","&","*","(",")"]

word = raw_input(">>")
words = word.split();
for w  in words:
    p = w.lower()
    if p in curse:
        filword=""
        worlen = len(w);
        for i in range(worlen):
            filword += fil[j]
            j = (j + 1)%len(fil)
        word = word.replace(w,filword);

print word

I have first splitted the line into a list called words. Now for every w in word, I have checked if it is there in curse list, if yes I have made a filword of length of the word. j = (j +1) % len(fil) is because the worlen can be greater than len(fil)and in that case you will have to reuse the characters. And then finally replaced the word.

PS : This code will fail on the cases like car, apple because it is splitting on basis of " ". IN such cases you can remove all the special characters other than " " and store it as another string as preprocessing and work on that string.

Upvotes: 1

Related Questions