Using Python

You have been hired by a small software company to create a "thesaurus" program that replaces words with their synonyms. The company has set you up with a sample thesaurus stored in a Python dictionary object. Here's the code that represents the thesaurus:

# define our simple thesaurus
thesaurus = {
"happy": "glad",
"sad" : "bleak"
}
The dictionary contains two keys - "happy" and "sad". Each of these keys holds a single synonym for that key.

Write a program that asks the user for a phrase. Then compare the words in that phrase to the keys in the thesaurus. If the key can be found you should replace the original word with a random synonym for that word. Words that are changed in this way should be printed in UPPERCASE letters. Make sure to remove all punctuation from your initial phrase so that you can find all possible matches. Here's a sample running of your program:

Enter a phrase: Happy Birthday! exclaimed the sad, sad kitten
GLAD birthday exclaimed the BLEAK BLEAK kitten

Respuesta :

Answer:

#section 1

import re

thesaurus = {

   "happy" : "glad",

   "sad" : "bleak",

   }

text =input('Enter text: ').lower()

#section 2

def synomReplace(thesaurus, text):

# Create a regular expression  from the dictionary keys

 regex = re.compile("(%s)" % "|".join(map(re.escape, thesaurus.keys())))

 

 # For each match, look-up corresponding value in dictionary

 return regex.sub(lambda x: thesaurus[x.string[x.start():x.end()]].upper(), text)

print(synomReplace(thesaurus, text))

Explanation:

#section 1

In this section, the regular expression module is imported to carry out special string operations. The thesaurus is initialized as a dictionary. The program then prompts the user to enter a text.

#section 2

In the section, we create a regular expression that will search for all the keys and another one that will substitute the keys with their value and also convert the values to uppercase using the .upper() method.

I have attached a picture for you to see the result of the code.

Ver imagen jehonor
ACCESS MORE