Skip to content

Instantly share code, notes, and snippets.

@dusnm
Created April 20, 2022 19:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dusnm/e98b91bc5e46bf43bda87cd1307a9866 to your computer and use it in GitHub Desktop.
Save dusnm/e98b91bc5e46bf43bda87cd1307a9866 to your computer and use it in GitHub Desktop.
Python "dictionary"
#!/usr/bin/env python3
import sys
import requests
from termcolor import colored
from requests.exceptions import JSONDecodeError
from typing import Dict, Union
def make_api_request(word: str) -> Union[Dict, None]:
url = f"https://api.dictionaryapi.dev/api/v2/entries/en/{word}"
response = requests.get(url)
if response.status_code != 200:
return None
try:
return response.json()
except JSONDecodeError:
return None
def get_user_input() -> Union[str, None]:
try:
input = sys.argv[1]
if len(input) == 0:
return None
return input
except IndexError:
return None
def main() -> None:
input = get_user_input()
if input is None:
print(colored('Invalid input.', 'red'), file=sys.stderr)
sys.exit(-1)
data = make_api_request(input)
if data is None or len(data) == 0:
print(colored('No data for word or word is invalid.', 'red'), file=sys.stderr)
sys.exit(-1)
for details in data:
word = colored(details['word'], 'green')
try:
phonetic = colored(details['phonetic'], 'yellow')
except KeyError:
phonetic = ''
for meaning in details['meanings']:
part_of_speech = colored(meaning['partOfSpeech'], 'cyan')
print(f"\n{word} {phonetic} {part_of_speech}\n")
for index, definition in enumerate(meaning['definitions']):
print(f"{index+1}. {definition['definition']}")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment