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!

4
  • how desireable output will look like? need positive control/test Commented May 8, 2016 at 18:06
  • and what is exactly the problem you want to solve? replace some words in phrase with synonyms? Commented May 8, 2016 at 18:10
  • When you split, it already returns a list, so you don't need to cast to list. Commented May 8, 2016 at 18:11
  • @aaaaaa edited the original post above Commented May 8, 2016 at 18:11

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

4 Comments

thanks! If I want the new word from the dictionary to be printed in caps, where would I add the ".upper()" ?
If only when the word is found, I'd use something like t = thesaurus[x].upper() if thesaurus.get(x) else x
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
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: stackoverflow.com/questions/59825/…. So in my example, draw from set(t) if x is found in the dictionaty.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.