3

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!

Danny Garcia
  • 227
  • 3
  • 19

1 Answers1

3

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)
JulienD
  • 7,102
  • 9
  • 50
  • 84
  • thanks! If I want the new word from the dictionary to be printed in caps, where would I add the ".upper()" ? – Danny Garcia May 08 '16 at 20:57
  • If only when the word is found, I'd use something like `t = thesaurus[x].upper() if thesaurus.get(x) else x` – JulienD May 08 '16 at 21:44
  • thanks! If i were to change the code to include more words associated to the key of the dictionary, for example, "sad" :["bleak", "blue", "depressed"] , how would I change the above answer to return a random word from the list within the dictionary? I am trying to include a popitem() but can't seem to place it in the right place within the code – Danny Garcia May 08 '16 at 22:53
  • Using pop() will remove the item from the dictionary, so it is not a good idea. Secondly, if you want a random element, either generate a random index to take an element from the list, or use a set and draw from it. This answer can be useful: http://stackoverflow.com/questions/59825/how-to-retrieve-an-element-from-a-set-without-removing-it. So in my example, draw from `set(t)` if `x` is found in the dictionaty. – JulienD May 09 '16 at 08:42