labyrinth-cs-proj/wordle/dictionary.py
2023-01-18 07:55:21 +05:30

98 lines
3.4 KiB
Python

import pickle
import json
import requests
with open("credentials.pickle", "rb") as f:
try:
while True:
d = pickle.load(f)
if d["credtype"] == "oxfordapi":
app_id = d["app_id"]
app_key = d["app_key"]
break
except EOFError:
pass
language = "en-us"
def defnsyn(w):
"""Returns definition and synonym of said word"""
f = open("log.txt", "a")
url = (
r"https://od-api.oxforddictionaries.com:443/api/v2/entries/"
+ language
+ "/"
+ w.lower()
)
r = requests.get(url, headers={"app_id": app_id, "app_key": app_key})
if r.status_code != 200:
f.write("GOT "+str(r.status_code))
return None, None
res = r.json()
f.write(json.dumps(res))
s1 = res["results"][0]["lexicalEntries"]
lexicalCategories = []
synonyms = []
defn = ""
try:
defn = res["entries"]["senses"]["definitions"][0]
if len(s1) > 1:
for i in range(len(s1)):
lexicalCategories.append(s1[i]["lexicalCategory"]["id"])
if "verb" in lexicalCategories:
baseindex = s1[lexicalCategories.index("verb")]["entries"][0]["senses"][
0
]
defn = baseindex["shortDefinitions"][0]
if "synonyms" in baseindex:
no = (
2
if len(baseindex["synonyms"]) > 3
else len(baseindex["synonyms"])
)
while no:
synonyms.append(baseindex["synonyms"][no]["text"])
no -= 1
synonyms.reverse()
elif "noun" in lexicalCategories:
baseindex = s1[lexicalCategories.index("noun")]["entries"][0]["senses"][
0
]
defn = baseindex["shortDefinitions"][0]
if "synonyms" in baseindex:
no = (
3
if len(baseindex["synonyms"]) > 3
else len(baseindex["synonyms"])
)
while no:
synonyms.append(baseindex["synonyms"][no]["text"])
no -= 1
synonyms.reverse()
else:
baseindex = s1[0]["entries"][0]["senses"][0]
defn = baseindex["shortDefinitions"][0]
if "synonyms" in baseindex:
no = (
3
if len(baseindex["synonyms"]) > 3
else len(baseindex["synonyms"])
)
while no:
synonyms.append(baseindex["synonyms"][no]["text"])
no -= 1
synonyms.reverse()
else:
baseindex = s1[0]["entries"][0]["senses"][0]
defn = baseindex["shortDefinitions"][0]
if "synonyms" in baseindex:
no = 3 if len(baseindex["synonyms"]) > 3 else len(baseindex["synonyms"])
while no:
synonyms.append(baseindex["synonyms"][no]["text"])
no -= 1
synonyms.reverse()
except:
print("err")
defn = synonyms = ""
return defn, synonyms