def generate_graph(graph): """ Generates the graph by pulling synonyms of the target word from Thesaurus.com (using PyDict). Afterwards, synonyms of those words are grabbed and added in as a second layer of the graph. This process is continued until the an antonym of the target word is found. Input: graph - an empty dict for the graph to be stored in Output: A completed graph as a dictionary of words and the synonyms they point to. """ global antonym prev_syns = [TARGET_WORD] print(PyDict.antonym(TARGET_WORD)) for syn in prev_syns: if any(i in prev_syns for i in PyDict.antonym(TARGET_WORD)): antonym_tempset = set(prev_syns).intersection(PyDict.antonym(TARGET_WORD)) antonym = list(antonym_tempset)[0] break if not graph.get(syn) and PyDict.synonym(syn): graph[syn] = PyDict.synonym(syn)[:NUM_SYNS] prev_syns += PyDict.synonym(syn)[:NUM_SYNS] return graph
def antonyms(self, x): x = x.replace('', '') dictionary = PyDictionary() try: print(dictionary.antonym(x)) return dictionary.antonym(x) except: return 'retry'
def meaning(word): try: dictionary = PyDictionary() blockPrint() data = dictionary.meaning(word) enablePrint() for key, value in data.items(): print() print(key+"\n") for i in value: print("- "+i) blockPrint() synonym = dictionary.synonym(word) enablePrint() blockPrint() antonym = dictionary.antonym(word) enablePrint() if(type(synonym) == type(None)): pass else: print("\nSynonym : "+str(synonym)) if(type(antonym) == type(None)): pass else: print("Antonym : "+str(antonym)+"\n") except: enablePrint() print("Sorry! "+word + " is not in English Dictionary. Please check the spelling...\n")
class Meaning(): def __init__(self): self.dictionary = PyDictionary() def meaning_function(self, query, task="mn"): #task can be meaning, translate, fo = open("meaning.txt", "w") if task == "mn": fo.write("Meaning :") fo.write(str(self.dictionary.meaning(query))) fo.write("Synonym :") fo.write(str(self.dictionary.synonym(query))) fo.write("Antonym :") fo.write(str(self.dictionary.antonym(query))) print(self.dictionary.meaning(query)) elif task == "tr": fo.write("Translation :") unicodedata.normalize('NFKD', self.dictionary.translate( query, 'hi')).encode('ascii', 'ignore') fo.write( unicodedata.normalize( 'NFKD', self.dictionary.translate(query, 'hi')).encode( 'ascii', 'ignore')) ##Unicode to string conversion print(self.dictionary.translate(query, 'hi')) fo.close() def __del__(self): os.remove("meaning.txt")
def dictionary(command): dictionary = PyDictionary() words = command.split() choice = words[0] word = str(words[-1]) print(choice) print(word) try: if choice == "define": definition = str(dictionary.meaning(word)) return (definition) elif choice == "synonyms": synonyms = dictionary.synonym(word) result = ', '.join(synonyms) print(result) return result elif choice == "antonyms": antonyms = dictionary.antonym(word) result = ', '.join(antonyms) print(result) return result else: return "Please retry your question" except TypeError: return ("Your word had no " + choice)
def dictionary(command): dictionary = PyDictionary() words = command.split() choice = words[0] word = str(words[-1]) print(choice) print(word) try: if choice == "define": definition = str(dictionary.meaning(word)) return(definition) elif choice == "synonyms": synonyms = dictionary.synonym(word) result = ', '.join(synonyms) print(result) return result elif choice == "antonyms": antonyms = dictionary.antonym(word) result = ', '.join(antonyms) print(result) return result else: return "Please retry your question" except TypeError: return ("Your word had no " + choice)
def antonym(word): try: word = word.lower() dictionary = PyDictionary() anto_list = (dictionary.antonym(word)) print("The antonym(s) of the word %s are:" % word) textToSpeech("The antonyms of the word that you entered are:") antonym = [] for i in range(0, len(anto_list)): antonym += [anto_list[i].encode('ascii')] print(str(i + 1) + ')' + anto_list[i].encode('ascii')) textToSpeech(antonym[i]) except TypeError: word_new = raw_input("Re-enter the word with the correct spelling: ") antonym(word_new)
class WordMeaningClass: def __init__(self, filename): self.filename = filename self.writename = filename[0:-9] + "meaning.txt" self.d = PyDictionary() def generate_meanings(self): with open(self.filename, "r") as f, open(self.writename, "a+") as w: for i, line in enumerate(f): if line.strip() != "": word = ( line.strip().lstrip('"').rstrip('"').strip().replace( "(", "").replace(")", "").replace(":", "").replace( ",", "").replace(".", "")) # word = "perils" # print(word) # for mean in d.meaning(word, disable_errors=True): # print(mean) # print(d.meaning(word, disable_errors=True)) out = "\n{}:\n{}\nSynonym:{}\nAntonym:{}\n".format( word, self.d.meaning(word, disable_errors=True), self.d.synonym(word), self.d.antonym(word), ) w.write(out) print(out) print("All word meanings saved to: {}".format(self.writename))
def word(request): search = request.GET['search'] dictionary = PyDictionary() meanings = dictionary.meaning(search).get('Noun') antonyms = dictionary.antonym(search) synonyms = dictionary.synonym(search) return render(request, 'word.html', {'search':search, 'meanings':meanings, 'antonyms':antonyms, 'synonyms':synonyms})
def searchForWord(self): _translate = QtCore.QCoreApplication.translate word = self.lineEdit_dictsearch_2.text() search_param = str(self.comboBox_lookup_2.currentText()) if (word == ""): self.label_dictresult.setText( _translate("MainWindow", "Enter search term!")) return dictionary = PyDictionary() print(dictionary.meaning(word)) self.label_dictresult.setText(_translate("MainWindow", "moretext")) if (search_param == "definition"): self.label_dictresult.setText( _translate("MainWindow", str(dictionary.meaning(word)))) elif (search_param == "synonym"): self.label_dictresult.setText( _translate("MainWindow", str(dictionary.synonym(word)))) else: self.label_dictresult.setText( _translate("MainWindow", str(dictionary.antonym(word))))
async def word(ctx): dictionary = PyDictionary() while True: try: ranWord = RandomWords() word = ranWord.get_random_word(hasDictionaryDef="true") print(word) meaning = dictionary.meaning(word) synonyms = dictionary.synonym(word) antonyms = dictionary.antonym(word) break except Exception: pass cleanMeaning = str(meaning).replace('{', '').replace('[', '').replace( ']', '').replace('}', '').replace("'", '') cleanSyns = str(synonyms).replace('[', '').replace(']', '').replace("'", '') cleanAnt = str(antonyms).replace('[', '').replace(']', '').replace("'", '') wordEmbed = discord.Embed(title=f"Random Word - {word.capitalize()}", description=f"{cleanMeaning}\n", color=0xB87DDF) wordEmbed.add_field(name="Synonyms", value=cleanSyns) wordEmbed.add_field(name="Antonyms", value=cleanAnt) await ctx.channel.send(embed=wordEmbed)
def word(request): search = request.GET.get('search') dictionary = PyDictionary() meaning = dictionary.meaning(search) synonyms = dictionary.synonym(search) antonyms = dictionary.antonym(search) context = {'meaning': meaning, 'synonyms': synonyms, 'antonyms': antonyms} return render(request, 'word.html', context)
class Dictionary: def __init__(self, bot): self.bot = bot self.dictionary = PyDictionary('lxml') #TODO a query like 'a;lskejf;laskjf;lkjvldskjrlgjslfgnhslkfnhsoifjosijosjeojsopejr' gives a valid response with an unknown subject. UNKNOWN FIX @commands.command(pass_context=True) async def meaning(self,ctx, word:str): """Return the meaning of a word""" ret = self.dictionary.meaning(word) if ret is None: #await self.bot.say("```Meaning for "+word+" not found.```") await self.bot.embed_this_for_me("Meaning for *"+word+"* not found", ctx) else: def_str = "" for k in ret.keys(): def_str +=k + ":\n" for i in ret[k][:3]: def_str += i + "\n" def_str += "\n" #await self.bot.say("```"+def_str+"```") await self.bot.embed_this_for_me(def_str, ctx) @commands.command(pass_context=True) async def stealthegg(self, ctx): await self.bot.delete_message(ctx.message) await self.bot.say(":eggplant:") @commands.command(pass_context=True) async def synonym(self,ctx, word:str): """Return the synonym of a word""" ret = self.dictionary.synonym(word) if ret is None: #await self.bot.say("```Synonym for "+word+" not found.```") await self.bot.embed_this_for_me("Synonym for *"+word+"* not found", ctx) else: def_str = "Synonyms for "+word+": " for j in ret: def_str += j + ", " # await self.bot.say("```"+def_str+"```") await self.bot.embed_this_for_me(def_str, ctx) @commands.command(pass_context=True) async def antonym(self,ctx, word:str): """Return the antonym of a word""" ret = self.dictionary.antonym(word) if ret is None: # await self.bot.say("```Antonym for "+word+" not found.```") await self.bot.embed_this_for_me("Antonym for *"+word+"* not found", ctx) else: def_str = "Antonyms for "+word+": " for j in ret: def_str += j + ", " # await self.bot.say("```"+def_str+"```") await self.bot.embed_this_for_me(def_str, ctx)
def antonym(): get_word = ent_word.get() word_antonym = PyDictionary.antonym(get_word) if word_antonym == None: word_format = "word does not exit." else: word_format = "{}".format("\n".join(word_antonym)) txt_dic.delete("1.0", "end") txt_dic.insert("1.0", word_format)
class Dictionary: """Word, yo""" def __init__(self, bot): self.bot = bot self.dictionary = PyDictionary() # self.lang = fileIO("data/dictionary/lang.json", "load") @commands.command(name="define", pass_context=True) async def define(self, ctx, *, word: str): """Displays definitions of a given word""" # TODO: Figure out why some values get cut off x = await self.bot.say("Searching...") search_term = word.split(" ", 1)[0] result = self.dictionary.meaning(search_term) str_buffer = "" if result is None: await self.bot.delete_message(x) await self.bot.say("This word is not in the dictionary.") return for key in result: str_buffer += "\n**" + key + "**: \n" counter = 1 j = False for val in result[key]: if val.startswith("("): str_buffer += str(counter) + ". *" + val + ")* " counter += 1 j = True else: if j: str_buffer += val + "\n" j = False else: str_buffer += str(counter) + ". " + val + "\n" counter += 1 print(str_buffer) await self.bot.delete_message(x) await self.bot.say(str_buffer) @commands.command(name="antonym", pass_context=True) async def antonym(self, ctx, *, word: str): """Displays antonyms for a given word""" await self.bot.say("Searching...") search_term = word.split(" ", 1)[0] result = self.dictionary.antonym(search_term) await self.bot.say("Antonyms for **" + search_term + "**: *" + "*, *".join(result) + "*") @commands.command(name="synonym", pass_context=True) async def synonym(self, ctx, *, word: str): """Displays synonyms for a given word""" await self.bot.say("Searching...") search_term = word.split(" ", 1)[0] result = self.dictionary.synonym(search_term) await self.bot.say("Synonyms for **" + search_term + "**: *" + "*, *".join(result) + "*")
def antonym(word): try: word = word.lower() dictionary = PyDictionary() anto_list = (dictionary.antonym(word)) print("The antonym(s) of the word %s are:" % word) for i in range(0, len(anto_list)): print(str(i + 1) + ')' + anto_list[i].encode('ascii')) except TypeError: word = raw_input("Re-enter the word with the correct spelling: ") antonym(word)
async def antonym(self, word): """Checks the dictionary for the antonyms for a given word.""" word = word.lower() result = dictionary.antonym(word) try: text = self.nym_text_format("antonyms", result, word) return await self.bot.say(text) except TypeError: return await self.bot.say("No results found. Are you " + "searching for a valid word?")
async def antonym(self, word): """Checks the dictionary for the antonyms for a given word.""" word = word.lower() result = dictionary.antonym(word) try: text = self.nym_text_format("antonyms", result, word) return await self.bot.say(text) except TypeError: return await self.bot.say("No results found. Are you " + "searching for a valid word?")
def antonym(word): try: word = word.lower() dictionary = PyDictionary() anto_list = (dictionary.antonym(word)) print("The antonym(s) of the word %s are:"%word) for i in range(0,len(anto_list)): print (str(i+1)+')'+anto_list[i].encode('ascii')) except TypeError: word = raw_input("Re-enter the word with the correct spelling: ") antonym(word)
def dictorize(x): list1,ss=[],"" for i in range (0,len(action)): if (action[i]=='"'): list1.append(i) catch1,catch2=list1[0],list1[1] for i in range (catch1+1,catch2): ss+=action[i] from PyDictionary import PyDictionary dictionary=PyDictionary() print ("Synonym: ",dictionary.synonym(ss),"\n"+"Antonym: ",dictionary.antonym(ss))
def get_related_words(keyword): dictionary = PyDictionary() related_words = [] for single_word in keyword.split(" "): synonyms = dictionary.synonym(single_word) antonyms = dictionary.antonym(single_word) if synonyms is not None: related_words.append(", ".join(synonyms)) if antonyms is not None: related_words.append(", ".join(antonyms)) return ", ".join(related_words)
def antonym(word): try: word = word.lower() dictionary = PyDictionary() anto_list = (dictionary.antonym(word)) print("The antonym(s) of the word %s are:"%word) for i in range(0,len(anto_list)): antonym += [anto_list[i].encode('ascii')] print (str(i+1)+')'+anto_list[i].encode('ascii')) textToSpeech(antonym[i]) except TypeError: print("Please re enter the world below with the right spelling! ")
class Dictionary(): def __init__(self): self.dictionary = PyDictionary() def meaning(self, text): de_word = [ "what", 'is', 'are', 'the', 'meanings', 'meaning', 'of', "a", "?", ".", "," ] word = get_stem(text, de_word) meaning = self.dictionary.meaning(word) gui.display(word.upper() + ':--') talk('meanings of ' + word + ' are ') key = list(meaning) for i in range(len(meaning)): gui.display(key[i] + ' -') talk('as a ' + key[i]) v = meaning[key[i]] for e in range(len(v)): gui.display('\n' + str(e + 1) + ') ' + v[e]) talk(v[e]) gui.display('\n') def antonym(self, text): de_word = [ "what", 'is', 'are', 'the', 'antonyms', 'antonym', 'of', "a", "?", ".", "," ] word = get_stem(text, de_word) antonym = self.dictionary.antonym(word) gui.display(word.upper() + ':--') talk('antonyms of ' + word + ' are ') for i in range(len(antonym)): gui.display(str(i + 1) + ') ' + antonym[i]) talk(antonym[i]) def synonym(self, text): de_word = [ "what", 'is', 'are', 'the', 'synonyms', 'synonym', 'of', "a", "?", ".", "," ] word = get_stem(text, de_word) synonym = self.dictionary.synonym(word) gui.display(word.upper() + ':--') talk('synonyms of ' + word + ' are ') for i in range(len(synonym)): gui.display(str(i + 1) + ') ' + synonym[i]) talk(synonym[i])
def word(request): search = request.GET.get('search') dictionary = PyDictionary() meaning = dictionary.meaning(search) synonym = dictionary.synonym(search) antonym = dictionary.antonym(search) context = { 'meaning': meaning['Noun'][0:4], 'synonym': synonym[0:11], 'antonym': antonym[0:11] } return render(request, 'word.html', context)
def problem4form_display(): # Note: run 'pip install PyDictionary' to run problem 4 code dictionary = PyDictionary() synonym_list = [] if request.method == 'POST' and request.form['definition'] == 'definition': definition = dictionary.meaning(request.form['word']) return str(definition) elif request.method == 'POST' and request.form['definition'] == 'synonym': synonym_list = dictionary.synonym(request.form['word']) return str(synonym_list) elif request.method == 'POST' and request.form['definition'] == 'antonym': antonym_list = dictionary.antonym(request.form['word']) return str(antonym_list)
def word(request): search = request.GET.get('search') # get by name dictionary = PyDictionary() meaning = dictionary.meaning(search) synonyms = dictionary.synonym(search) antonyms = dictionary.antonym(search) context = { 'meaning': meaning['Noun'][0], 'synonyms': synonyms, 'antonyms': antonyms, 'hello': 'hell' } return render(request, 'word.html', context)
def search(): t1.delete("1.0", "end") t2.delete("1.0", "end") t3.delete("1.0", "end") t4.delete("1.0", "end") dictionary = PyDictionary() ip = entry.get() try: a = dictionary.meaning(ip) pos = a.keys() meaning = a.values() n = 0 try: for i in meaning: t1.insert(END, i[0] + '\n') n += 1 if n > 2: break except: pass try: for j in pos: t2.insert(END, j + ', ') except: pass except: t1.delete("1.0", "end") t1.insert(INSERT, 'Not Found.....') return try: n = 0 synonyms = dictionary.synonym(ip) for i in synonyms: t3.insert(END, i + '\n') n += 1 if n > 5: break except: pass try: n = 0 antonyms = dictionary.antonym(ip) for i in antonyms: t4.insert(END, i + '\n') n += 1 if n > 5: break except: pass
def _convert_word(word): """Helper function to create/assign synonyms, antonyms, and parts of speech.""" dictionary = PyDictionary() try: ### create synonyms # get the synonyms synonyms = filter(_filter_words, dictionary.synonym(word.word)) synonym_through = Word.synonyms.through synonym_objs =[] # assign the synonyms for synonym in synonyms: synonym_objs.append(synonym_through(from_word=word, to_word=Word.objects.get_or_create(word=synonym)[0])) # create the synonyms synonym_through.objects.bulk_create(synonym_objs) ### create antonyms # get the synonyms antonyms = dictionary.antonym(word.word) if antonyms: # some words have no antonyms antonym_through = Word.antonyms.through antonym_objs = [] # assign the synonyms for antonym in filter(_filter_words, antonyms): antonym_objs.append(antonym_through(from_word=word, to_word=Word.objects.get_or_create(word=antonym)[0])) # create the synonyms antonym_through.objects.bulk_create(antonym_objs) ### most likely retrieve and assign parts of speech, but potentially create pos_through = Word.part_of_speech.through pos_through_objs = [] # get the parts of speech pos = list(dictionary.meaning(word.word).keys()) # assign the parts fo speech for part_of_speech in pos: pos_through_objs.append(pos_through(word=word, partofspeech=PartOfSpeech.objects.get_or_create(category=part_of_speech)[0])) # create the parts of speech pos_through.objects.bulk_create(pos_through_objs) ### return the newly created word return JsonResponse({ 'word': { 'word': word.word, 'synonyms': list(word.synonyms.values('id', 'word')), 'antonyms': list(word.antonyms.values('id', 'word')), 'part_of_speech': list(word.part_of_speech.values('id', 'category')), } }) except TypeError: return HttpResponseBadRequest("Something went wrong when coverting an existing word to a full word - most likely a fake word was passed in.")
def return_output(value, word): dictionary = PyDictionary() output = "" if value == "1": output = dictionary.meaning(word) elif value == "2": output = dictionary.synonym(word) elif value == "3": output = dictionary.antonym(word) else: pass return output
def dictionary_result(term): """ Takes an input string and returns a dictionary with the orignal term, meaning, synonym and antonyms request : https://pl-backend-staging.herokuapp.com/dict/compress/ response : { "term": "compress", "term_meaning": { "Noun": [ "a cloth pad or dressing (with or without medication", "to relieve discomfort or reduce fever" ], "Verb": [ "make more compact by or as if by pressing", "squeeze or press together" ] }, "term_synonym": [ "abbreviate", "shorten", "restrict", "wrap", "cram" ], "term_antonym": [ "amplify", "enlarge", "increase", "lengthen", "grow" ] } """ # creating instance of the PyDictionary dictionary = PyDictionary() return_data = {} # dictionary keys return_data['term'] = term # returns the meaning of the term return_data['term_meaning'] = dictionary.meaning(term) # returns the synonyms of the term return_data['term_synonym'] = dictionary.synonym(term) # returns the antonyms of the term return_data['term_antonym'] = dictionary.antonym(term) return return_data
def word(request): search = request.GET.get('search') dictionary = PyDictionary() meanings = dictionary.meaning(search) synonyms = dictionary.synonym(search) antonyms = dictionary.antonym(search) context = { 'meanings': meanings['Noun'][0:4], 'search':search, 'synonyms':synonyms[0:10], 'antonyms':antonyms, } return render(request,'dictionary/word.html',context)
def dictionary(self): # Returns meaning, synonym and antonym of any word Dict = PyDictionary() print_say('\nEnter word', self) word = input() print('\nMeaning : ' + str(Dict.googlemeaning(word))) blockPrint() syn = Dict.synonym(word) ant = Dict.antonym(word) if syn is not None: syn = [x.encode('UTF8') for x in syn] if ant is not None: ant = [x.encode('UTF8') for x in ant] enablePrint() print('\nSynonyms : ' + str(syn)) print('\nAntonyms : ' + str(ant))
async def antonym_wrd(message: Message): """antonym of word""" await message.edit("`Searching for antonyms...`") word = message.input_str or message.reply_to_message.text if not word: await message.err("no input!") else: dictionary = PyDictionary() words = dictionary.antonym(word) output = f"**Antonym for :** __{word}__\n" try: for a in words: output = output + f"• __{a}__\n" await message.edit(output) except Exception: await message.err(f"Couldn't fetch antonyms of {word}")
class Meaning(): def __init__(self): self.dictionary=PyDictionary() def meaning_function(self,query,task="mn"): #task can be meaning, translate, fo=open("meaning.txt","w") if task == "mn" : fo.write("Meaning :") fo.write(str(self.dictionary.meaning(query))) fo.write("Synonym :") fo.write(str(self.dictionary.synonym(query))) fo.write("Antonym :") fo.write(str(self.dictionary.antonym(query))) print (self.dictionary.meaning(query)) elif task =="tr": fo.write("Translation :") unicodedata.normalize('NFKD', self.dictionary.translate(query,'hi')).encode('ascii','ignore') fo.write(unicodedata.normalize('NFKD', self.dictionary.translate(query,'hi')).encode('ascii','ignore')) ##Unicode to string conversion print(self.dictionary.translate(query,'hi')) fo.close() def __del__(self): os.remove("meaning.txt")
flag = 1 if (flag == 0 ): print "Tweet successful" else: print "Tweet Failed" elif " ".join(message.strip().lower().split()[:2]) == "synonym of": bot_response = dictionary.synonym(" ".join(message.strip().lower().split()[2:])) if(len(bot_response) >= 1 ): bot_response = ", ".join(bot_response) else: bot_response = "Sorry i couldn't find the synonym for "," ".join(bot_response) print bot_response elif " ".join(message.strip().lower().split()[:2]) == "antonym of": bot_response = (dictionary.antonym(" ".join(message.strip().lower().split()[2:]))) if(len(bot_response) >= 1 ): bot_response = ", ".join(bot_response) else: bot_response = "Sorry i couldn't find the antonym for "," ".join(bot_response) print bot_response elif " ".join(message.strip().lower().split()[:2]) == "meaning of": bot_response = dictionary.meaning(" ".join(message.strip().lower().split()[2:])) if len (bot_response.keys()) == 0 : bot_response = "Sorry, Couldn't find the meaning " else: if 'Noun' in bot_response.keys(): print bot_response['Noun'][0] else: