Using PythonThe company quickly realized that the simple two-word thesaurus was
ID: 3769824 • Letter: U
Question
Using PythonThe company quickly realized that the simple two-word thesaurus was far too small. In order to address this shortcoming they have provided you with a very large text file that contains over 30,000 words. Copy this text-only thesaurus and save it in a file named python_asg10_Roget_Thesaurus.txt.
Every word occupies its own line followed by a comma-separated list of synonyms. Every word can have a potentially unlimited # of synonyms. Your task for this part is to open this file and parse it into a Python dictionary object so that it functions just like the simple thesaurus from the previous part. Here's a sample running of your program:
Hint: For each word you will need to create a new list that contains all the synonyms for that word. You can then store this list in the dictionary using the word as the key.
Explanation / Answer
worddict = {}
#read file contents
## Open the file with read only permit
f = open('D:/ravi/Cheg/python_asg10_Roget_Thesaurus.txt', "r")
## use readlines to read all lines in the file
lines = f.readlines()
## close the file after reading the lines.
f.close()
#Parse each line
for str in lines:
# print(str)
tokens = str.split(",")
count = 0
key = tokens[0]
worddict[key] = tokens[1:]
print("Key : %s" %key)
print(worddict)
-----------------output------------------
Key : word1
Key : word2
Key : word3
{'word3': ['synonym1', 'synonym2', '...', 'synonymN-1', 'synonymN'], 'word1': ['synonym1', 'synonym2', '...', 'synonymN-1', 'synonymN '], 'word2': ['synonym1', 'synonym2', '...', 'synonymN-1', 'synonymN ']}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.