Advertisement
Guest User

sadasd

a guest
Dec 9th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.67 KB | None | 0 0
  1. import requests
  2. import sys
  3. import json
  4. import os
  5. import logging
  6.  
  7. logging.basicConfig(filename='synonymsAPI.log', format='%(asctime)s - %(message)s', level=logging.INFO)
  8.  
  9. inputWord = sys.argv[1]
  10. inputMax = sys.argv[2]
  11. synonyms = {}
  12. path = "synonyms.json"
  13.  
  14. def synonyms_get(word, max):
  15. headers = {
  16. 'X-RapidAPI-Key': 'bf02cdb9a7msh5aaaa5372b0f9b2p134436jsn29de29f01fbe'
  17. }
  18. parameters = {
  19. "ml": word,
  20. "max": max
  21. }
  22. try:
  23. response = requests.get('https://api.datamuse.com/words', params=parameters)
  24. except requests.exceptions.RequestException as e:
  25. logging.error("Exception occurred", exc_info=True)
  26. print(e)
  27. sys.exit(1)
  28.  
  29. if(response.status_code == requests.codes.ok):
  30. logging.info('Got data from API for word: '+ word)
  31. data = response.json()
  32. for element in data:
  33. del element['tags']
  34. #print(data)
  35. return data
  36.  
  37. def readJSON(path):
  38. global synonyms
  39. if os.path.exists('synonyms.json'):
  40. with open(path, 'r') as json_file:
  41. try:
  42. data = json.load(json_file)
  43. #print(data)
  44. synonyms = data
  45. return data
  46. except Exception as e:
  47. logging.error("Exception occurred", exc_info=True)
  48. print("error %s on readJSON()" % e)
  49. else:
  50. with open(path, 'w') as json_file:
  51. try:
  52. data = synonyms_get('nice', 5)
  53. synonym = {'nice': data}
  54. json.dump(synonym, json_file)
  55. synonyms = synonym
  56. return synonym
  57. except Exception as e:
  58. logging.error("Exception occurred", exc_info=True)
  59. print("error %s on readJSON()" % e)
  60.  
  61. def saveToJSON(data, path):
  62. global synonyms
  63. with open(path, 'w') as json_file:
  64. try:
  65. synonym = {inputWord: data}
  66. synonyms.update(synonym)
  67. json.dump(synonyms, json_file)
  68. except Exception as e:
  69. logging.error("Exception occurred", exc_info=True)
  70. print("error %s on saveToJSON" % e)
  71.  
  72. def main(filePath, word):
  73. global synonyms, inputWord, inputMax
  74. readJSON(filePath)
  75. if word in synonyms:
  76. logging.info("Word: " + word + " already saved, file did not change")
  77. print("Word: " + word + " already saved, file did not change")
  78. else:
  79. logging.info("Word: " + word + " not found, getting data from API")
  80. print("Word: " + word + " not found, getting data from API")
  81. saveToJSON(synonyms_get(inputWord, inputMax), filePath)
  82.  
  83. main(path, inputWord)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement