I have downloaded a 5MB data base consisting of words and their meanings in a json file . I want to write a python progrsm which will ask the user to enter a word and then the program will search through the database and retuen back the meaning of the word . There can be instances when there are two or three different meanings for a word. The program will display all the different meanings of the word.
I wanted to make the program little intelligent. What if the user spells he word incorrectly while entering the word? Suppose he wants to know the meaning of 'crowd' but by mistake he types in 'crowded'. The system will be intelligent enough to suggest few words nearest to the word 'crowdd' which he has typed and let the user choose the right word which he meant from the list of suggesstions.
Also , there are checks for cases - upper case, lower case etc.
Let us see the code now and then run the program to see the outputs:
Here is the python code which you have been eaiting for so long:
import json
from difflib import get_close_matches
data = json.load(open("data.json"))
print(data)
def translate(w):
w = w.lower()
if w in data:
return data[w]
if w in data:
return data[w]
elif w.title() in data: # user entered "maryland" will check for "Maryland" as well
return data[w.title()]
elif w.upper() in data:
return data[w.upper()]
elif len(get_close_matches(w,data.keys()))>0:
yn= input("Did you mean %s instead?. EnterY if yes, or N if no: "% get_close_matches(w,data.keys())[0])
if yn=='Y':
return data[get_close_matches(w,data.keys())[0]]
elif yn =='N':
return("the word does not exist")
else:
return ('We did not understand your entry')
else:
return("the word does not exist")
word = input("Enter word")
output =translate(word)
if type(output) == list:
for item in output:
print(item)
else:
print(output)
Let us test out different scenarios now :
Input: data["crowd"]
Output: ['A large number of people united for some specific purpose.', 'A crowd of people pressed close together in a small space.', '6-string musical instrument of Welsh or Irish origin and played with a bow.', 'A large group of people.', 'To cause to herd, drive, or crowd together.', 'To fill or occupy in a small space to the point of overflowing.', 'To gather together in large numbers.']
Input:
Enter word crowdd
Input: N
Output: the word does not exist
Another scenario. Suppose the User does not type the whole word but abbreviation like 'USA' or 'UK'.
How does our dictionary program find out the meaning in such case?
Input: Let us try out: Enter word UK
Output: A country in Western Europe (comprising Wales, Scotland, England and Northern Ireland) with the capital London.
This is a simple program to show you how to write simple Applications using Python.
Stay tuned to my Lessons. Next Lesson I will show you how to write another interesting interactive application
using Python.