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)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容