|
@@ -0,0 +1,87 @@
|
|
|
+#! /usr/bin/python3.7
|
|
|
+import requests
|
|
|
+import sys
|
|
|
+import textwrap
|
|
|
+
|
|
|
+# USE UR OWN API KEY
|
|
|
+API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
|
|
|
+REQUEST_URI = "https://www.dictionaryapi.com/api/v3/references/collegiate/json/{word}?key={key}"
|
|
|
+
|
|
|
+def convert_italics(string):
|
|
|
+ # M-W returns etymology responses with italics in the
|
|
|
+ # form {it}italic{/it}. This converts it to terminal-
|
|
|
+ # friendly markup.
|
|
|
+ new_open_tags = string.replace('{it}', '\033[3m')
|
|
|
+ new_close_tags = new_open_tags.replace('{/it}', '\033[00m\033[30m')
|
|
|
+ return new_close_tags
|
|
|
+
|
|
|
+def print_help():
|
|
|
+ print("""USAGE:
|
|
|
+
|
|
|
+ $ mw word
|
|
|
+
|
|
|
+ Where `word` is the word you want defined.
|
|
|
+ """)
|
|
|
+
|
|
|
+def print_suggestions(json):
|
|
|
+ print('Given word not found. Did you mean one of these?\n')
|
|
|
+ cols = 4
|
|
|
+ for idx, suggestion in enumerate(json):
|
|
|
+ if (idx + 1) % cols == 0:
|
|
|
+ print(suggestion)
|
|
|
+ else:
|
|
|
+ tab = ' '
|
|
|
+ tab = tab[:20 - len(suggestion)]
|
|
|
+ print(suggestion + tab, end='')
|
|
|
+ print()
|
|
|
+
|
|
|
+def print_definition(json):
|
|
|
+ for case in range(len(json)):
|
|
|
+ word = json[case]['meta']['id']
|
|
|
+ try:
|
|
|
+ part_of_speech = json[case]['fl']
|
|
|
+ except KeyError:
|
|
|
+ part_of_speech = ""
|
|
|
+ syllables = json[case]['hwi']['hw']
|
|
|
+ try:
|
|
|
+ pronunciation = json[case]['hwi']['prs'][0]['mw']
|
|
|
+ except KeyError:
|
|
|
+ pronunciation = ""
|
|
|
+
|
|
|
+ print('\033[1m{word}\033[0m ({pos})'.format(word=word, pos=part_of_speech))
|
|
|
+ print(' {syllables} | {pronunciation}\n'.format(syllables=syllables,
|
|
|
+ pronunciation=pronunciation))
|
|
|
+
|
|
|
+ for idx, shortdef in enumerate(json[case]['shortdef']):
|
|
|
+ print(str(idx + 1) + ". " + textwrap.fill(shortdef, subsequent_indent=' '))
|
|
|
+
|
|
|
+
|
|
|
+ try:
|
|
|
+ etymology = json[case]['et'][0][1]
|
|
|
+ print('\n')
|
|
|
+ print('HISTORY, ETYMOLOGY')
|
|
|
+ print(convert_italics(etymology))
|
|
|
+ except KeyError:
|
|
|
+ pass
|
|
|
+ print()
|
|
|
+
|
|
|
+
|
|
|
+if len(sys.argv) < 2:
|
|
|
+ print_help()
|
|
|
+ sys.exit(0)
|
|
|
+
|
|
|
+if sys.argv[1] == '-h' or sys.argv[1] == '--help':
|
|
|
+ print_help()
|
|
|
+ sys.exit(0)
|
|
|
+
|
|
|
+word_to_define = sys.argv[1]
|
|
|
+
|
|
|
+definition_json = requests.get(REQUEST_URI.format(word=word_to_define,
|
|
|
+ key=API_KEY)).json()
|
|
|
+
|
|
|
+if 'meta' not in definition_json[0]:
|
|
|
+ # Given word not in dict. Returned suggestions.
|
|
|
+ print_suggestions(definition_json)
|
|
|
+else:
|
|
|
+ print_definition(definition_json)
|
|
|
+
|