Censoring a text string using a dictionary and replacing words with Xs. Python -
i'm trying make simple program takes string of text t , list of words l , prints text words in l replaced number of xs corresponding letters in word.
problem: code replaces parts of words match words in l. how can make target whole words?
def censor(t, l): cenword in l: number_of_x = len(cenword) sensurliste = {cenword : ("x"*len(cenword))} cenword, x in sensurliste.items(): word = t.replace(cenword, x) t = word.replace(cenword, x) print (word)
first of all, believe want have loops on same level, when 1 completes other starts.
secondly, looks have code doesn't anything.
for example, sensurliste
ever have censored words, paired "x" string. therefore first loop unneeded because trivial create "x" string on spot in second loop.
then, saying word = t.replace(cenword,x) t=word.replace(cenword,x)
the second line nothing, because word
already has instances of cenword replaced. so, can shortened just
t = t.replace(cenword,x);
finally, problem is, python replace method doesn't care word boundaries. replace instances of cenword no matter if full word or not.
you use regex make find instances of full words, however, use more along lines of
def censort(t,l): words = t.split() #split words list in range(len(words)): #for each word in text if words[i] in l: #if needs censoredx words[i] = "x"*len(words[i]) #replace x's t=words.join() #rejoin list string
Comments
Post a Comment