mw 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. #! /usr/bin/python3.7
  2. import requests
  3. import sys
  4. import textwrap
  5. # USE UR OWN API KEY
  6. API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
  7. REQUEST_URI = "https://www.dictionaryapi.com/api/v3/references/collegiate/json/{word}?key={key}"
  8. def convert_italics(string):
  9. # M-W returns etymology responses with italics in the
  10. # form {it}italic{/it}. This converts it to terminal-
  11. # friendly markup.
  12. new_open_tags = string.replace('{it}', '\033[3m')
  13. new_close_tags = new_open_tags.replace('{/it}', '\033[00m\033[30m')
  14. return new_close_tags
  15. def print_help():
  16. print("""USAGE:
  17. $ mw word
  18. Where `word` is the word you want defined.
  19. """)
  20. def print_suggestions(json):
  21. print('Given word not found. Did you mean one of these?\n')
  22. cols = 4
  23. for idx, suggestion in enumerate(json):
  24. if (idx + 1) % cols == 0:
  25. print(suggestion)
  26. else:
  27. tab = ' '
  28. tab = tab[:20 - len(suggestion)]
  29. print(suggestion + tab, end='')
  30. print()
  31. def print_definition(json):
  32. for case in range(len(json)):
  33. word = json[case]['meta']['id']
  34. try:
  35. part_of_speech = json[case]['fl']
  36. except KeyError:
  37. part_of_speech = ""
  38. syllables = json[case]['hwi']['hw']
  39. try:
  40. pronunciation = json[case]['hwi']['prs'][0]['mw']
  41. except KeyError:
  42. pronunciation = ""
  43. print('\033[1m{word}\033[0m ({pos})'.format(word=word, pos=part_of_speech))
  44. print(' {syllables} | {pronunciation}\n'.format(syllables=syllables,
  45. pronunciation=pronunciation))
  46. for idx, shortdef in enumerate(json[case]['shortdef']):
  47. print(str(idx + 1) + ". " + textwrap.fill(shortdef, subsequent_indent=' '))
  48. try:
  49. etymology = json[case]['et'][0][1]
  50. print('\n')
  51. print('HISTORY, ETYMOLOGY')
  52. print(convert_italics(etymology))
  53. except KeyError:
  54. pass
  55. print()
  56. if len(sys.argv) < 2:
  57. print_help()
  58. sys.exit(0)
  59. if sys.argv[1] == '-h' or sys.argv[1] == '--help':
  60. print_help()
  61. sys.exit(0)
  62. word_to_define = sys.argv[1]
  63. definition_json = requests.get(REQUEST_URI.format(word=word_to_define,
  64. key=API_KEY)).json()
  65. if 'meta' not in definition_json[0]:
  66. # Given word not in dict. Returned suggestions.
  67. print_suggestions(definition_json)
  68. else:
  69. print_definition(definition_json)