python-exercise-1

# Import library
import json
from difflib import get_close_matches

data = json.load(open("data.json"))


def retrieve_definition(word):
    word = word.lower()
    # Check for non existing words
    # 1st elif: To make sure the program return the definition of words that start with a capital letter
    # (e.g. Delhi, Texas)
    # 2nd elif: To make sure the program return the definition of acronyms (e.g. USA, NATO)
    # 3rd elif: To find a similar word
    # -- len > 0 because we can print only when the word has 1 or more close matches
    # -- In the return statement, the last [0] represents the first element from the list of close matches
    if word in data:
        return data[word]
    elif word.title() in data:
        return data[word.title()]
    elif word.upper() in data:
        return data[word.upper()]
    elif len(get_close_matches(word, data.keys())) > 0:
        action = input("Did you mean %s instead? [y or n]: " % get_close_matches(word, data.keys())[0])
        # -- If the answers is yes, retrieve definition of suggested word
        if action == "y":
            return data[get_close_matches(word, data.keys())[0]]
        elif action == "n":
            return "The word doesn't exist, yet."
        else:
            return "We don't understand your entry. Apologies."


# Input from user
word_user = input("Enter a word: ")

# Retrieve the definition using function and print the result
output = retrieve_definition(word_user)

# If a word has more than one definition, print them recursively
if type(output) == list:
    for item in output:
        print("-", item)
# For words having single definition
else:
    print("-", output)

你可能感兴趣的:(python-exercise-1)