Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace multiple words in string with dictionary (python)

I want the user to input a phrase, and when the words "happy"/"sad" are within the phrase, I want the program to return those words replaces with their values in the dictionary. Here is my code:

# dictionary
thesaurus = {
              "happy": "glad",
              "sad"  : "bleak"
            }

# input
phrase = input("Enter a phrase: ")

# turn input into list
part1 = phrase.split()
part2 = list(part1)

# testing input
counter = 0
for x in part2:
    if part2[counter] in thesaurus.keys():
        phrase.replace(part2[counter], thesaurus.values()) # replace with dictionary value???
        print (phrase)
    counter += 1

The code works except I can't seem to figure out how to replace multiple words to get the program to print the replaced words.

So if the user enters

"Hello I am sad" 

the desired output would be

"Hello I am bleak"

Any help would be appreciated!

like image 995
Danny Garcia Avatar asked Feb 20 '26 08:02

Danny Garcia


1 Answers

Translate all words in the input sentence, then join the translated parts:

translated = []
for x in part2:
    t = thesaurus.get(x, x)  # replaces if found in thesaurus, else keep as it is
    translated.append(t)

newphrase = ' '.join(translated)
like image 195
JulienD Avatar answered Feb 21 '26 22:02

JulienD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!