I want my program to print only one random word from a list in my dictionary, but I cannot get the correct syntax for this. I tried using popitem () to get a random value from a list, but it does not seem to work. Here is my code:
import random
thesaurus = {
"happy":["glad", "blissful", "ecstatic", "at ease"],
"sad" :["bleak", "blue", "depressed"]
}
phrase = input("Enter a phrase: ")
part1 = phrase.split()
part2 = list(part1)
newlist = []
for x in part2:
s = thesaurus.get(x, x)
newlist.append(s)
print (newlist)
For example, if the input
i am happy
The expected result will be
i am glad
or any random word from a list in a dictionary.
But now my conclusion is as follows:
['i', 'am', ['glad', 'blissful', 'ecstatic', 'at ease']]
I know that a different thread is associated with this, but it does not seem to affect this specific problem.
Any help would be appreciated!
edit:
If I extended this formula to work with an imported file with a long list of words, how do I change the code?
newDict = {}
with open('thesaurus.txt', 'r') as f:
for line in f:
splitLine = line.split()
newDict[(splitLine[0])] = ",".join(splitLine[1:])
print ("Total words in thesaurus: ", len(newDict))
# input
phrase = input("Enter a phrase: ")
# turn input into list
part1 = phrase.split()
part2 = list(part1)
# testing input
newlist = []
for x in part2:
s = newDict[x].pop() if x in newDict else x
s = random.choice(newDict[x]).upper() if x in newDict else x
newlist.append(s)
newphrase = ' '.join(newlist)
print (newphrase)
Sample line text in the thesaurus file:
abash,humility,fear