Danny Garcia Danny Garcia - 2 years ago 170
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!

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download