Danny Garcia Danny Garcia - 5 months ago 28x
Python Question

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!


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

newphrase = ' '.join(translated)