DeepBlue/api/thesaurus.py

60 lines
1.8 KiB
Python
Raw Normal View History

2020-01-10 19:39:45 +01:00
import requests
import re, random
2020-01-10 20:23:22 +01:00
import nltk
2020-01-10 19:39:45 +01:00
from util import logging, config
key = config.settings["api_keys"]["thesaurus"]
url = f"http://thesaurus.altervista.org/thesaurus/v1?key={key}&language=en_US&output=json&word="
def thesaurufy_sentence(sentence):
2020-01-10 20:23:22 +01:00
symbols = nltk.word_tokenize(sentence)
tags = nltk.pos_tag(symbols)
2020-01-10 19:39:45 +01:00
if len(symbols) == 0:
return ""
for i in range(0, len(symbols)):
if not symbols[i].isalpha():
continue
2020-01-10 20:23:22 +01:00
if tags[i][1] != "NN" and tags[i][1] != "VB" and tags[i][1] != "VBG" and tags[i][1] != "VBP" and tags[i][1] != "JJ" and tags[i][1] != "RB":
symbols[i] = " " + symbols[i]
continue
2020-01-10 19:39:45 +01:00
response = requests.get(url + symbols[i])
if not response.ok:
# logging.warning(f"Thesaurus API returned {response.status_code} ({url + symbols[i]})")
symbols[i] = " " + symbols[i]
continue
responses = response.json()["response"]
2020-01-10 20:23:22 +01:00
condition = ""
if tags[i][1] == "JJ":
condition = "(adj)"
elif tags[i][1] == "RB":
condition = "(adv)"
elif tags[i][1] == "NN":
condition = "(noun)"
else:
condition = "(verb)"
try:
words = random.choice([a for a in responses if a["list"]["category"] == condition])["list"]["synonyms"].split("|")
except:
symbols[i] = " " + symbols[i]
continue
# print(words)
2020-01-10 19:39:45 +01:00
word = words[random.randint(0, len(words) - 1)]
if "(" in word:
if "antonym" in word.split("(")[1].lower():
symbols[i] = " " + symbols[i]
continue
2020-01-10 20:23:22 +01:00
2020-01-10 19:39:45 +01:00
word = word.split("(")[0][:-1]
symbols[i] = " " + word
return "".join(symbols)