def DictExpandQuery(q_terms, k=5): dic = PyDictionary() new_terms = [] for term in q_terms: if isStopWord(term): continue # check if word exists in the dictionary w_found = True try: dic.meaning(term) except: w_found = False # get k first synonyms if w_found: try: synonyms = dic.synonym(term) except: continue if synonyms == None: continue if len(synonyms) > k: synonyms = synonyms[:k] new_terms.extend(synonyms) new_query_terms = q_terms + new_terms return new_query_terms
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(word): i=0 #while (1): print word dictionary=PyDictionary() dict=dictionary.meaning(word) if dict is not None: espeak.synth("your word is " + word) time.sleep(2.5) if ( dict.has_key('Adjective')) : s= dict['Adjective'] if len(s)>=i : print s[i] l= len(s[i]) t = l /12.0 espeak.synth("(adjective)" + s[i]) time.sleep(t) if dict.has_key('Noun') : s= dict['Noun'] if len(s)>=i : print s[i] l= len(s[0]) t = l /12.0 espeak.synth("(NOUN)" + s[i]) time.sleep(t) if dict.has_key('Verb') : s= dict['Verb'] if len(s)>=i : print s[i] l= len(s[i]) t = l /12.0 espeak.synth("VERB" + s[i]) time.sleep(t) if dict.has_key('Adverb') : s= dict['Adverb'] if len(s)>=i : print s[i] l= len(s[i]) t = l /12.0 espeak.synth("(ADVERB)" + s[i]) time.sleep(t) if dict.has_key('Preposition') : s= dict['Preposition'] if len(s)>=i : print s[i] l= len(s[i]) t = l /12.0 espeak.synth("(PREPO)" + s[i]) time.sleep(t) print 5
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(word): i=0 while (1): dictionary=PyDictionary() dict=dictionary.meaning(word) if (dict.has_key('Adjective')) : s= dict['Adjective'] if len(s)>=i : print s[i] l= len(s[i]) t = l /12.0 espeak.synth("(adjective)" + s[i]) time.sleep(t) if dict.has_key('Noun') : s= dict['Noun'] if len(s)>=i : print s[i] l= len(s[0]) t = l /12.0 espeak.synth("(NOUN)" + s[i]) time.sleep(t) if dict.has_key('Verb') : s= dict['Verb'] if len(s)>=i : print s[i] l= len(s[i]) t = l /12.0 espeak.synth("VERB" + s[i]) time.sleep(t) if dict.has_key('Adverb') : s= dict['Adverb'] if len(s)>=i : print s[i] l= len(s[i]) t = l /12.0 espeak.synth("(ADVERB)" + s[i]) time.sleep(t) if dict.has_key('Preposition') : s= dict['Preposition'] if len(s)>=i : print s[i] l= len(s[i]) t = l /12.0 espeak.synth("(PREPO)" + s[i]) time.sleep(t) espeak.synth("If alternate meaning required, give a double tap within the next 3 seconds")
def handle(text, mic, profile): lst = text.split() text = lst[len(lst)-1] if(text): dictionary=PyDictionary() mean = dictionary.meaning(text) if not mean: mic.say("I'm sorry I couldn't find the meaning of the word "+text) return mic.say(text) for keys in mean: mic.say(keys) lst = mean[keys] for l in lst: mic.say(l)
async def dictionary(self, word): """Checks the dictionary for the meanings of a given word.""" word = word.lower() try: result = dictionary.meaning(word) nountext = self.meaning_text_format("Noun", result) verbtext = self.meaning_text_format("Verb", result) adjtext = self.meaning_text_format("Adjective", result) advtext = self.meaning_text_format("Adverb", result) except TypeError: return await self.bot.say("No results found. Are you " + "searching for a valid word?") text = "\n" + nountext + verbtext + adjtext + advtext definition = "Found the following definitions for **" + word + "**:" \ + text return await self.bot.say(definition)
dictionary = PyDictionary() s = "" old_s = "" while (s != "0"): s = input("Word / option: ") print("") if s == "1": if old_s == "": print("No previous records") else: print(dictionary.synonym(old_s)) print() continue result = str(dictionary.meaning(s)) if "list index out of range" in result: print("Try again") else: print(result) old_s = s print("") print("Byeth")
def game(): time.sleep(0.5) print("\nselect the mode you want to play:\n") print(" 1.Easy \n 2.Medium \n 3.Difficult") mode = input() while True: if mode == "Easy" or mode == "1": print("You selected Easy mode!!!!!") print("\nStart guessing...") words = [ "lion", "tiger", "leopard", "elephant", "Rabbit", "goat", "hornbill", "cucumber", "lotus", "orchid", "Jackfruit", "wheat", "maize", "ginger", "crocodile", "wax", "punjab", "srilanka", "srinagar", "jammu and kashmir", "kerala", "Andhrapradesh", "telangana", "odisha", "Assam", "goa", "tamilnadu", "potato", "noodles", "crabs", "earthworms", "scissors", "knife", "glass", "happy", "sad", "emotion" ] n = len(words) #print(n) idx = random.randint(1, n) word = words[idx] dictionary = PyDictionary() hint = dictionary.meaning(word) print("\nHint is ", hint) guesses = '' turns = 5 while turns > 0: failed = 0 for char in word: if char in guesses: print((char + " "), end="") else: print("_ ", end="") failed += 1 if failed == 0: print("\nYou won the game!!!!!") game() else: guess = input("\n\nguess a character:") guesses += guess if guess not in word: turns -= 1 print("Your guess is Wrong!!!") print("You have", +turns, 'more guesses') if turns == 0: print("\n You Lose the game") print("The word is ", word) print("Do you want to play again?") ans = input() if ans == "n" or ans == "N": print("Thanks for playing!!!") return else: game() elif mode == "Medium" or mode == "2": print("You selected Medium mode!!!!!") print("\nStart guessing...") words = [ "annoy", "ignore", "prefer", "attention", "instead", "problem", "calm", "investigate", "protect", "comfortable", "invite", "proud", "consequences", "important", "question", "curious", "jealous", "reminds", "curve", "leader", "repeat", "decide", "list", "report", "directions", "listen", "rhyme", "discover", "lovely", "respect", "disappointed", "measuring", "searching", "embarrassed", "miserable", "special", "enormous", "mumble", "spotless", "exhausted", "negative", "squirm", "explore", "nervous", "stomped", "fair", "nibbled", "suddenly", "fascinating", "note", "suggestion", "feast", "notice", "surprise", "focus", "observing", "uncomfortable", "opposite", "warning", "gigantic", "ordinary", "wonder", "grumpy", "positive", "worried", "huge", "precious" ] word = random.choice(words) dictionary = PyDictionary() hint = dictionary.meaning(word) print("\nHint is ", hint) guesses = '' turns = 5 while turns > 0: failed = 0 for char in word: if char in guesses: print((char + " "), end="") else: print("_ ", end="") failed += 1 if failed == 0: print("\nYou won the game!!!!!") game() else: guess = input("\n\nguess a character:") guesses += guess if guess not in word: turns -= 1 print("Your guess is Wrong!!!") print("You have", +turns, 'more guesses') if turns == 0: print("\n You Lose the game") print("The word is ", word) print("Do you want to play again?") ans = input() if ans == "n" or ans == "N": print("Thanks for playing!!!") return else: game() elif mode == "Difficult" or mode == "3": print("You selected Difficult mode!!!!!") print("\nStart guessing...") words = [ "abruptly", "absurd", "abyss", "affix", "askew", "avenue", "awkward", "axiom", "azure", "bagpipes", "bandwagon", "banjo", "bayou", "beekeeper", "blitz", "blizzard", "boggle", "bookworm", "boxcar", "boxful", "buckaroo", "buffalo", "buffoon", "buxom", "buzzard", "buzzing", "buzzwords", "caliph", "cobweb", "cockiness", "croquet", "crypt", "curacao", "cycle", "daiquiri", "dirndl", "disavow", "dizzying", "duplex", "dwarves", "embezzle", "equip", "espionage", "euouae", "exodus", "faking", "fishhook", "fixable", "fjord", "flapjack", "flopping", "fluffiness", "flyby", "foxglove", "frazzled", "frizzled", "fuchsia", "funny", "gabby", "galaxy", "galvanize", "gazebo", "giaour", "gizmo", "glowworm", "glyph", "gnarly", "gnostic", "gossip", "grogginess", "haiku", "haphazard", "hyphen", "iatrogenic", "icebox", "injury", "ivory", "ivy", "jackpot", "jaundice", "jawbreaker", "jaywalk", "jazziest", "jazzy", "jelly", "jigsaw", "jinx", "jiujitsu", "jockey", "jogging", "joking", "jovial", "joyful", "juicy", "jukebox", "jumbo", "kayak", "kazoo", "keyhole", "khaki", "kilobyte", "kiosk", "kitsch", "kiwifruit", "klutz", "knapsack", "larynx", "lengths", "lucky", "luxury", "lymph", "marquis", "matrix", "megahertz", "microwave", "mnemonic", "mystify", "naphtha", "nightclub", "nowadays", "numbskull", "nymph", "onyx", "ovary", "oxidize", "oxygen", "pajama", "peekaboo", "phlegm", "pixel", "pizazz", "pneumonia", "polka", "pshaw", "psyche", "puppy", "puzzling", "quartz", "queue", "quips", "quixotic", "quiz", "quizzes", "quorum", "razzmatazz", "rhubarb", "rhythm", "rickshaw", "schnapps", "scratch", "shiv", "snazzy", "sphinx", "spritz", "squawk", "staff", "strength", "strengths", "stretch", "stronghold", "stymied", "subway", "swivel", "syndrome", "thriftless", "thumbscrew", "topaz", "transcript", "transgress", "transplant", "triphthong", "twelfth", "twelfths", "unknown", "unworthy", "unzip", "uptown", "vaporize", "vixen", "vodka", "voodoo", "vortex", "voyeurism", "walkway", "waltz", "wave", "wavy", "waxy", "wellspring", "wheezy", "whiskey", "whizzing", "whomever", "wimpy", "witchcraft", "wizard", "woozy", "wristwatch", "wyvern", "xylophone", "yachtsman", "yippee", "yoked", "youthful", "yummy", "zephyr", "zigzag", "zigzagging", "zilch", "zipper", "zodiac", "zombie" ] word = random.choice(words) dictionary = PyDictionary() hint = dictionary.meaning(word) print("\nHint is ", hint) guesses = '' turns = 5 while turns > 0: failed = 0 for char in word: if char in guesses: print((char + " "), end="") else: print("_ ", end="") failed += 1 if failed == 0: print("\nYou won the game!!!!!") game() else: guess = input("\n\nguess a character:") guesses += guess if guess not in word: turns -= 1 print("Your guess is Wrong!!!") print("You have", +turns, 'more guesses') if turns == 0: print("\n You Lose the game") print("The word is ", word) print("Do you want to play again?") ans = str(input()) if (ans == "n" or ans == "N"): return else: game() else: print("Select valid mode:") mode = input()
async def pls_define(ctx, word): # noqa: C901 if words(word) == False: dictionary = PyDictionary() try: defined = dictionary.meaning(f"{word}") if defined.get('Noun', 99) != 99: bye1 = defined['Noun'] await ctx.send("Noun meaning(s):") for i in range(0, len(bye1)): await asyncio.sleep(1) await ctx.channel.send(f"{i+1}. {bye1[i]}") if defined.get('Verb', 99) != 99: bye2 = defined['Verb'] await ctx.send("Verb meaning(s):") for i in range(0, len(bye2)): await asyncio.sleep(1) await ctx.channel.send(f"{i+1}. {bye2[i]}") if defined.get('Pronoun', 99) != 99: bye3 = defined['Pronoun'] await ctx.send("Pronoun meaning(s):") for i in range(0, len(bye3)): await asyncio.sleep(1) await ctx.channel.send(f"{i+1}. {bye3[i]}") if defined.get('Adjective', 99) != 99: bye4 = defined['Adjective'] await ctx.send("Adjective meaning(s):") for i in range(0, len(bye4)): await asyncio.sleep(1) await ctx.channel.send(f"{i+1}. {bye4[i]}") if defined.get('Adverb', 99) != 99: bye5 = defined['Adverb'] await ctx.send("Adverb meaning(s):") for i in range(0, len(bye5)): await asyncio.sleep(1) await ctx.channel.send(f"{i+1}. {bye5[i]}") if defined.get('Preposition', 99) != 99: bye6 = defined['Preposition'] await ctx.send("Preposition meaning(s):") for i in range(0, len(bye6)): await asyncio.sleep(1) await ctx.channel.send(f"{i+1}. {bye6[i]}") if defined.get('Conjunction', 99) != 99: bye7 = defined['Conjunction'] await ctx.channel.send("Conjunction meaning(s):") for i in range(0, len(bye7)): await asyncio.sleep(1) await ctx.send(f"{i+1}. {bye7[i]}") if defined.get('Interjection', 99) != 99: bye8 = defined['Interjection'] await ctx.channel.send("Interjection meaning(s):") for i in range(0, len(bye8)): await asyncio.sleep(1) await ctx.send(f"{i+1}. {bye8[i]}") if defined.get('Numeral', 99) != 99: bye9 = defined['Numeral'] await ctx.channel.send("Numeral meaning(s):") for i in range(0, len(bye9)): await asyncio.sleep(1) await ctx.send(f"{i+1}. {bye9[i]}") if defined.get('Article', 99) != 99: bye10 = defined['Article'] await ctx.send("Article meaning(s):") for i in range(0, len(bye10)): await asyncio.sleep(1) await ctx.channel.send(f"{i+1}. {bye10[i]}") if defined.get('Determiner', 99) != 99: bye11 = defined['Determiner'] await ctx.send("Determiner meaning(s):") for i in range(0, len(bye11)): await asyncio.sleep(1) await ctx.channel.send(f"{i+1}. {bye11[i]}") else: pass except Exception: await ctx.send(f"`{word.capitalize()}` is not in this dictionary.") elif ctx.channel.is_nsfw() == True: dictionary = PyDictionary() try: defined = dictionary.meaning(f"{word}") if defined.get('Noun', 99) != 99: bye1 = defined['Noun'] await ctx.send("Noun meaning(s):") for i in range(0, len(bye1)): await asyncio.sleep(1) await ctx.channel.send(f"{i+1}. {bye1[i]}") if defined.get('Verb', 99) != 99: bye2 = defined['Verb'] await ctx.send("Verb meaning(s):") for i in range(0, len(bye2)): await asyncio.sleep(1) await ctx.channel.send(f"{i+1}. {bye2[i]}") if defined.get('Pronoun', 99) != 99: bye3 = defined['Pronoun'] await ctx.send("Pronoun meaning(s):") for i in range(0, len(bye3)): await asyncio.sleep(1) await ctx.channel.send(f"{i+1}. {bye3[i]}") if defined.get('Adjective', 99) != 99: bye4 = defined['Adjective'] await ctx.send("Adjective meaning(s):") for i in range(0, len(bye4)): await asyncio.sleep(1) await ctx.channel.send(f"{i+1}. {bye4[i]}") if defined.get('Adverb', 99) != 99: bye5 = defined['Adverb'] await ctx.send("Adverb meaning(s):") for i in range(0, len(bye5)): await asyncio.sleep(1) await ctx.channel.send(f"{i+1}. {bye5[i]}") if defined.get('Preposition', 99) != 99: bye6 = defined['Preposition'] await ctx.send("Preposition meaning(s):") for i in range(0, len(bye6)): await asyncio.sleep(1) await ctx.channel.send(f"{i+1}. {bye6[i]}") if defined.get('Conjunction', 99) != 99: bye7 = defined['Conjunction'] await ctx.channel.send("Conjunction meaning(s):") for i in range(0, len(bye7)): await asyncio.sleep(1) await ctx.send(f"{i+1}. {bye7[i]}") if defined.get('Interjection', 99) != 99: bye8 = defined['Interjection'] await ctx.channel.send("Interjection meaning(s):") for i in range(0, len(bye8)): await asyncio.sleep(1) await ctx.send(f"{i+1}. {bye8[i]}") if defined.get('Numeral', 99) != 99: bye9 = defined['Numeral'] await ctx.channel.send("Numeral meaning(s):") for i in range(0, len(bye9)): await asyncio.sleep(1) await ctx.send(f"{i+1}. {bye9[i]}") if defined.get('Article', 99) != 99: bye10 = defined['Article'] await ctx.send("Article meaning(s):") for i in range(0, len(bye10)): await asyncio.sleep(1) await ctx.channel.send(f"{i+1}. {bye10[i]}") if defined.get('Determiner', 99) != 99: bye11 = defined['Determiner'] await ctx.send("Determiner meaning(s):") for i in range(0, len(bye11)): await asyncio.sleep(1) await ctx.channel.send(f"{i+1}. {bye11[i]}") else: pass except Exception: await ctx.send(f"`{word.capitalize()}` is not in this dictionary.") else: await ctx.send("You can only send NSFW things in NSFW channels.")
# Make sure to first install PyDictionary with "pip install PyDictionary" # Ever have a huge list of words to define? Don't feel like using Google and constantly waste precious time by deleting the # old word and typing in the new one? Well, with this simple, barely working script, you don't have to delete that old word! # Now you can just type the new one in and instantly get your result! Sure, it's not a lot of time saved, but it all adds up, # right? from PyDictionary import PyDictionary # PyDictionary is a dictionary module that's easy to use with Python dictionary = PyDictionary() while True: print("What do you want to know the definition of?\n") word = input() print(dictionary.meaning(word)) word = ""
class DictionaryIndicator: def __init__(self): #dictionary related self.dictionary_offline=PyDictionary() #appindicator related self.indicator=appindicator.Indicator("dictionary-indicator", gtk.STOCK_SPELL_CHECK, appindicator.CATEGORY_APPLICATION_STATUS) self.indicator.set_status(appindicator.STATUS_ACTIVE) self.indicator.set_attention_icon("Dictionary") self.start() self.indicator.set_menu(self.menu) def start(self): # start a dictionary window self.menu=gtk.Menu() self.dictionary=gtk.MenuItem("Start Dictionary") self.dictionary.connect("activate", self.openWindow) self.dictionary.show() self.menu.append(self.dictionary) # exit button self.quit_button=gtk.MenuItem("Quit") self.quit_button.connect("activate", self.quit) self.quit_button.show() self.menu.append(self.quit_button) def main(self): self.start() gtk.main() def openWindow(self, widget): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.set_title("Dictionary") self.window.set_size_request(300, 150) # container box self.vbox=gtk.VBox(False, 0) self.window.add(self.vbox) self.vbox.show() #input self.textbox=gtk.Entry() self.textbox.set_max_length(30) self.textbox.set_text("Enter word here") self.vbox.pack_start(self.textbox, True, True, 0) self.textbox.show() #output self.results=gtk.Entry() self.results.set_max_length(300) self.results.set_text("Meanings appear here") self.vbox.pack_start(self.results, True, True, 0) self.results.show() self.find_meaning=gtk.Button(stock=gtk.STOCK_DIALOG_QUESTION) self.find_meaning.connect("clicked", self.meaning) self.find_meaning.show() self.vbox.pack_start(self.find_meaning, True, True, 0) self.window.show() def meaning(self, widget): words=self.textbox.get_text() words_to_find_meaning = re.split('[^a-zA-Z0-9]',words) meanings="" for w in words_to_find_meaning: for key, val in self.dictionary_offline.meaning(w).items(): if(len(val) > 0): meanings+=val[0] else: meanings+="Not found" break meanings+=";" self.results.set_text(meanings) def quit(self, widget): print "hell came here" sys.exit(0)
class English: """English dictionary. Attributes: TypeMeanings: Type of the returned meanings from `meanings()`. TypeDefinition: Type of the returned definition from `define()`. """ # https://mypy.readthedocs.io/en/latest/cheat_sheet.html TypeMeanings = Dict[str, List[str]] TypeDefinition = Dict[str, Union[List[str], TypeMeanings]] def __init__(self): # type: () -> None """Initialize the dictionaries.""" self._spell = Spell('en_US') self._dictionary = PyDictionary('html.parser') _log.debug('Initialized %s instance correctly', type(self).__name__) def check(self, word): # type: (str) -> bool """Check if a word is in the English dictionary. Args: word: The word to check. Returns: True if it is and False otherwise. """ out = self._spell.check(word) # type: bool return out def suggest(self, misspelled_word): # type: (str) -> List[str] """Suggest corrections for a misspelled word. Args: misspelled_word: The word to use. Returns: A list of suggestions. """ out = self._spell.suggest(misspelled_word) # type: List[str] return out def meanings(self, word): # type: (str) -> English.TypeMeanings """Get the meanings of a word if they exists. Args: word: The word to use. Returns: A list of meanings. """ with CaptureStdStreams(): out = self._dictionary.meaning( word) # type: Optional[English.TypeMeanings] if out is None: _log.debug('Could not find any meaning to %s', word) return {} return out def synonyms(self, word): # type: (str) -> List[str] """Get the synonyms of a word if they exists. Args: word: The word to use. Returns: A list of synonyms. """ with CaptureStdStreams(): out = self._dictionary.synonym(word) # type: Optional[List[str]] if out is None: _log.debug('Could not find any synonym to %s', word) return [] return out def antonyms(self, word): # type: (str) -> List[str] """Get the antonyms of a word if they exists. Args: word: The word to use. Returns: A list of synonyms. """ with CaptureStdStreams(): out = self._dictionary.antonym(word) # type: Optional[List[str]] if out is None: _log.debug('Could not find any antonym to %s', word) return [] return out def define(self, word): # type: (str) -> English.TypeDefinition """Define a word and find its synonyms and antonyms. Args: word: The word to define. Returns: A dict of meanings, synonyms and antonyms. """ out = { 'Meanings': self.meanings(word), 'Synonyms': self.synonyms(word), 'Antonyms': self.antonyms(word), } # type: English.TypeDefinition # we have to put the above type comment because mypy cannot # infer the type correctly. Instead, it infers # `Dict[str, Collection[str]]`. However, we can do: # `return {...}` and it would infer it correctly. return out
def syno(word): dictionary=PyDictionary() return (dictionary.meaning(word))
robot_response = "okay!" elif "today" in you: if "weather" in you: robot_response = "Current temperature is " + str(forecast.currently.temperature) + "\n" robot_response += "In the next few hour, " + forecast.hourly.summary + '\n' robot_response += "And this week will be " + forecast.daily.summary else: robot_response = "Today is " + today.strftime("%B %d, %Y") elif "time" in you: robot_response = datetime_Hanoi.strftime("%H hours %M minutes %S seconds") elif "what does" in you and "mean" in you: wordSpl = you.split(' ') word = dictionary.meaning(wordSpl[-2]) if word is None: robot_response = "I can't not find it in the dictionary" else: robot_response = "Check out what I have found" for wordType, meanings in word.items(): print(wordType + ": ") for meaning in meanings: print(" - " + meaning) elif "search for" in you: search = you.split('search for ')[-1] try: overallInfo = wikipedia.summary(search, sentences=2) print(overallInfo) print("URL: " + wikipedia.page(search).url)
try: with sr.Microphone() as source: # use the default microphone as the audio source audio = r.listen(source) sentence=r.recognize_google(audio) print('I heard that you said:\n',sentence) except: sentence=input('Enter a sentence (we could not figure out what you said)') google_username = "******" google_password = "******" path = "" sent=[] for elem in sentence.split(' '): pier=dictionary.meaning(elem) if 'Noun' in str(pier): if len(pier)==1: sent.append(elem) pie=[] real=[] loopy=0 tea=[] if len(sent)>3: for elem in sent: loopy=loopy+1 tea.append(elem) if loopy==3: loopy=0 pie.append(','.join(tea)) tea=[]
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: print "Not found" #tasks elif message.strip().split()[0].lower() == 'tasks' : bot_response = ''
# currently just the list of matched words text_output = class_list.__str__() # Parts of speech recognition tokens = nltk.word_tokenize(class_str) dictionary = PyDictionary() nouns = [] verbs = [] adjectives = [] otherPos = [] for word in tokens: definition = dictionary.meaning(word) # https://pypi.python.org/pypi/PyDictionary/1.3.4 assignment = definition.keys()[0] # Get the part of speech from the dictonary # assignment = tuple[1] if assignment == 'Noun': nouns.append(word) elif assignment == 'Verb': verbs.append(word) elif assignment == 'Adjective': adjectives.append(word) else: otherPos.append(word) # Create the grammar
def dictionary(word): if word == "": ad.tts("Didn't get the word") return; d = enchant.Dict("en_GB") if not d.check(word): word = d.suggest(word)[0] if word[-1] == '.': word= word[0:-1] i=0 print word dictionary=PyDictionary() dict=dictionary.meaning(word) while (1): c=0 if dict is not None: ad.tts("your word is " + word) if ( dict.has_key('Adjective')) : s= dict['Adjective'] if len(s)>i : print s[i] ad.tts("adjective, " + s[i]) c=1 if dict.has_key('Noun') : s= dict['Noun'] if len(s)>i : print s[i] ad.tts("Noun, " + s[i]) c=1 if dict.has_key('Verb') : s= dict['Verb'] if len(s)>i : print s[i] ad.tts("Verb, " + s[i]) c=1 if dict.has_key('Adverb') : s= dict['Adverb'] if len(s)>i : print s[i] ad.tts("Adverb, " + s[i]) c=1 if dict.has_key('Preposition') : s= dict['Preposition'] if len(s)>=i : print s[i] ad.tts("Preposition, " + s[i]) c=1 i=i+1 if c==0: ad.tts("sorry, no more meanings available") break else: ad.tts("sorry, the meaning is not available") break ad.tts("Do you want an alternate meaning?" ) while (1): cmmd=ad.stt() if cmmd == None: continue elif ad.find(cmmd, "yes") or ad.find(cmmd, "yeah"): break elif ad.find(cmmd, "no"): return; return;
# add this word to the current list of candidates candidates.append(word) # else the edit distance is greater than the lower edit distance and we just want to move on else: continue print ("") print(candidates) print ("") # now that we have a list of candidates, let's show what the difference is for candidate in candidates: d=difflib.Differ() diff=d.compare(french,candidate) print (' '.join(diff)) print (dictionary.meaning(candidate)) print ('') #for line in difflib.context_diff(french, candidate): # sys.stdout.write(line) ##example #def comparison(french,a_words[i]): #set_french= Counter(french) #set_a_words[i]=Counter(a_words[i]) #common= set_french &set_a_words[i] #if len(a_words[i])>7: #comparison(french,a_words[i])
sent=[] for elem in t: fee=[] tre=elem.split(' ') for eem in tre: if eem!='' and eem!='/n': fee.append(eem) sent.append(fee) l=[] real=[] var=0 for elem in sent: l=[] var=0 for ele in elem: fr=dictionary.meaning(ele) try: fr=list(fr.keys()) try: l.append(mode(fr)) except StatisticsError: l.append(fr[0]) print(l) except AttributeError: var=1 if var==0: real.append(l)
""" A script to solve the game "Word Cookies" by calculating the permutation of the letters and finding a valid English word from that. Author: Nahom Abi Email: [email protected] """ from itertools import permutations from PyDictionary import PyDictionary dictionary = PyDictionary() letters = raw_input('Input Letters (separated by comma): ').split(',') length = int(raw_input('Input length of word: ')) perms = permutations(letters, length) for perm in perms: word = ''.join(perm) try: meaning = dictionary.meaning(word) print 'Found word:', word except Error as e: pass
def fill_models(apps, schema): Word = apps.get_model('sampleapp', 'Word') PartOfSpeech = apps.get_model('sampleapp', 'PartOfSpeech') dictionary = PyDictionary() def myFunc(x): if x.count(' ') or x.count('-'): return False else: return True words = [ "hello", "goodbye", "life", "gargantuan", "run", "slow", "water", "imagination", "science", "realistic" ] parts_of_speech = set() word_objs = [] word_id_map = {} i = 0 pos_id_map = {} pos_objs = [] for word in words: word_objs.append(Word(word=word, id=i)) word_id_map[word] = i i += 1 parts_of_speech.update(list(dictionary.meaning(word).keys())) for k, pos in enumerate(parts_of_speech): if pos not in pos_id_map: pos_objs.append(PartOfSpeech(category=pos, id=k)) pos_id_map[pos] = k synonym_through = Word.synonyms.through antonym_through = Word.antonyms.through pos_through = Word.part_of_speech.through synonym_objs = [] antonym_objs = [] pos_through_objs = [] for word in words: pos = list(dictionary.meaning(word).keys()) synonyms = filter(myFunc, dictionary.synonym(word)) for synonym in synonyms: if synonym not in word_id_map: word_objs.append(Word(word=synonym, id=i)) word_id_map[synonym] = i i += 1 synonym_objs.append( synonym_through(from_word_id=word_id_map[word], to_word_id=word_id_map[synonym])) antonyms = dictionary.antonym(word) if antonyms: for antonym in filter(myFunc, antonyms): if antonym not in word_id_map: word_objs.append(Word(word=antonym, id=i)) word_id_map[antonym] = i i += 1 antonym_objs.append( antonym_through(from_word_id=word_id_map[word], to_word_id=word_id_map[antonym])) for part_of_speech in pos: pos_through_objs.append( pos_through(word_id=word_id_map[word], partofspeech_id=pos_id_map[part_of_speech])) Word.objects.bulk_create(word_objs) PartOfSpeech.objects.bulk_create(pos_objs) synonym_through.objects.bulk_create(synonym_objs) antonym_through.objects.bulk_create(antonym_objs) pos_through.objects.bulk_create(pos_through_objs)
class Dictionary: def __init__( self, bot): # This allows the cog to access the bot, and its functions self.bot = bot self.pydictionary = PyDictionary() @commands.command(pass_context=True, aliases=["dict", "dic", "define", "def", "meaning"]) async def dictionary(self, ctx, word): await asyncio.sleep(0.05) await ctx.message.delete() embed = discord.Embed( title="Dictionary", description="Here is what I found for `{}`: \n\n___".format(word), color=COLOR) meaning = self.pydictionary.meaning(word) if safe_get_list(meaning, "Noun", False): embed.add_field( name="Noun", value=str('`1.` ' + safe_get_list( safe_get_list(meaning, "Noun"), 0, "").capitalize() + '\n`2.` ' + safe_get_list(safe_get_list(meaning, "Noun"), 1, "").capitalize()), inline=False) if safe_get_list(meaning, "Verb", False): embed.add_field( name="Verb", value=str('`1.` ' + safe_get_list( safe_get_list(meaning, "Verb"), 0, "").capitalize() + '\n`2.` ' + safe_get_list(safe_get_list(meaning, "Verb"), 1, "").capitalize()), inline=False) if safe_get_list(meaning, "Adjective", False): embed.add_field( name="Adjective", value=str('`1.` ' + safe_get_list( safe_get_list(meaning, "Adjective"), 0, "").capitalize() + '\n`2.` ' + safe_get_list(safe_get_list(meaning, "Adjective"), 1, "").capitalize()), inline=False) if safe_get_list(meaning, "Adverb", False): embed.add_field( name="Adverb", value=str('`1.` ' + safe_get_list( safe_get_list(meaning, "Adverb"), 0, "").capitalize() + '\n`2.` ' + safe_get_list(safe_get_list(meaning, "Adverb"), 1, "").capitalize()), inline=False) await ctx.send(embed=embed)
def dictionary(word): if word == "": ad.tts("I Didn't get the word") return; d = enchant.Dict("en_GB") if not d.check(word): word = d.suggest(word)[0] if word[-1] == '.': word= word[0:-1] i=0 print word dictionary=PyDictionary() dict=dictionary.meaning(word) while (1): c=0 if dict is not None: ad.tts("your word is " + word) if ( dict.has_key('Adjective')) : s= dict['Adjective'] if len(s)>i : print s[i] ad.tts("adjective, " + s[i]) c=1 if dict.has_key('Noun') : s= dict['Noun'] if len(s)>i : print s[i] ad.tts("Noun, " + s[i]) c=1 if dict.has_key('Verb') : s= dict['Verb'] if len(s)>i : print s[i] ad.tts("Verb, " + s[i]) c=1 if dict.has_key('Adverb') : s= dict['Adverb'] if len(s)>i : print s[i] ad.tts("Adverb, " + s[i]) c=1 if dict.has_key('Preposition') : s= dict['Preposition'] if len(s)>=i : print s[i] ad.tts("Preposition, " + s[i]) c=1 i=i+1 if c==0: ad.tts("sorry, no more meanings available") break else: ad.tts("sorry, meaning is not available") break ad.tts("Do you want an alternate meaning?" ) while (1): cmmd=ad.stt() if cmmd == None: continue elif ad.find(cmmd, "yes") or ad.find(cmmd, "yeah"): break elif ad.find(cmmd, "no"): return; return;
def word_meaning(word): dictionary = PyDictionary() word_mean = dictionary.meaning(word) if word_mean is None: word_mean["Noun"] = "No description of this word" return word_mean
from PyDictionary import PyDictionary as pd # User Input Section print("Enter The Word To Get Its Meaning") usr_inpt = input(":-") # Fetching Section core = pd.meaning(usr_inpt) # For Getting The Type keys = str(core.keys()) key_strt_cut = keys[12::1] key_end_cut = key_strt_cut.replace("\'])", "") print("Type Of The Word Is = ", key_end_cut) # For Getting The Meaning meanings = str(core.values()) means = str(meanings[14:200:1]) print("This are the meaning of the word you entered==") print(means) # Ending Code print("\n Enter Any Character And Press Enter To Exit") input(":-") exit()
@author: SRINIVAS """ """ import urllib from bs4 import BeautifulSoup url = "http://weather.weatherbug.com/MN/Wahkon-weather.html?zcode=z6286&zip=56386" soup = BeautifulSoup(urllib.request.urlopen(url).read()) a=soup.find(name="span", id="divHi").get_text() b=soup.find(name="span", id="divLo").get_text() """ from PyDictionary import PyDictionary dictionary=PyDictionary() import speech_recognition as sr r = sr.Recognizer() with sr.Microphone() as source: # use the default microphone as the audio source audio = r.listen(source) # listen for the first phrase and extract it into audio data try: a=r.recognize_google(audio) except LookupError: # speech is unintelligible print("Could not understand audio") s=a.split(' ') der=-1 trte=0 if len(s)==2 and s[0]=='Define': srer=s[1] fret=dictionary.meaning(srer).items() for elem in fret: print(elem[0],'\n',elem[1][0])
def simplify(sentence, index, tokens, exceptions=[None, ''], personaliser=None): word = tokens[index] pos = get_pos_tag(tokens, index) tense = get_tense(word, pos) t0 = time() synset = get_disambiguated_synset(sentence, word, None) synonyms = get_synonyms(word, synset) #+ oxf_synonyms.get_synonyms(word) print 'Time for Synonyms:', time() - t0 exceptions += get_exceptions(word) print 'Exceptions:', exceptions t0 = time() clean_stripped_synonyms = clean_list(synonyms, exceptions) stripped_synonyms = tense_or_define(index, tokens, clean_stripped_synonyms, tense) print 'Time for Stripped Synonyms:', time() - t0 if stripped_synonyms is None or len(stripped_synonyms) == 0: return define(word, synset), None print 'Tense:', tense print 'Stripped Synonyms:', stripped_synonyms print 'Defnition:', dict.meaning(word) t0 = time() simplest_word = get_simplest(stripped_synonyms) # if simplest_word != word: # stripped_synonyms = filter(lambda a: a != word, stripped_synonyms) # simplest_word = get_best_after_rank(stripped_synonyms, word) # simplest_word = '' # if personaliser is not None: # print 'Simple Predictions' # for synonym in stripped_synonyms : # prediction = personaliser.predict(synonym) # if prediction == 0: # print 'Simple Word:', synonym # simplest_word = synonym print 'Time for Simplest Word:', time() - t0 if simplest_word == None: return word, None stored_word = simplest_word simplest_word = apply_tense(simplest_word, tense) print 'Simplest Word After Tense:', simplest_word if simplest_word in exceptions: exceptions.append(stored_word) simplification = simplify(sentence, index, tokens, exceptions=exceptions) simplest_word = simplification[0] article = simplification[1] print 'Simple Word:', simplest_word article = get_article(simplest_word, tokens, index) print 'Article:', article set_article(tokens, index, article) if simplest_word.lower() == word.lower(): return define(word, synset), article elif ' ' in simplest_word: return word + ' (' + simplest_word + ')', article else: return simplest_word.upper(), article
from PyDictionary import PyDictionary dictionary= PyDictionary() print (dictionary.meaning("indentation"))
speak(f'Your name is {user_name}') elif 'what is your age' in que: que=que.replace(que,'') speak('My age is not defined') speak('Ask anything rather then the personal question, Please') elif 'meaning' in que: que=str(que) w=que.split(' ') word=w[-1] w=w.clear() que=que.replace(que,'') speak(f"Just wait,Finding the meaning of {word}") di=PyDictionary() mean=di.meaning(word,disable_errors=True) mm=mean.get('Noun') mmm=mm[0] speak(f'The meaning of {word} is {mmm}') elif 'close' in que: que=que.replace(que,'') speak('What do you want to close sir') w=Listen() if 'code' in w or 'vs code' in w: speak('code is closing sir') os.system('taskkill /f /im'+' Code.exe') elif 'chrome browser' in w: speak('chrome browser is closing sir') os.system('taskkill /f /im'+' Chrome.exe')
class Data(object): """Contains all the data functions to display the answer, definition, and choices""" def __init__(self, words=None): if not words: self.words = self.collect_words() else: self.words = self.words self.lookup = PyDictionary() def collect_words(self, word_file="gre_game/gre_word_file.txt"): """Builds the word database""" with open(word_file) as wordlist: wordlist = wordlist.read().splitlines() return wordlist def display_words(self): """Test function to make sure self.collect_words() function worked correctly.""" for word in self.words: print(word) def get_answer(self): """Chooses a random word from the wordlist and removes the word from the list to prevent repeats""" while True: try: answer_idx = random.randint(0, len(self.words) - 1) except Exception: print('Error retrieving word. Trying again...') continue break return self.words.pop(answer_idx).lower() def definition(self, answer): """Queries the definition of the answer""" while True: try: query = self.lookup.meaning(answer) break # If there's no result (NoneType) except TypeError: continue print('\nDefinition: \n') for definition in query: print(definition, '\n', ', '.join(query[definition])) print('-' * 75 + '\n') def choices(self,answer, num=False): """Builds a list consisting of the answer and 3 other random words""" my_choices = [answer] while len(my_choices) < 4: choice = random.choice(self.words) if choice not in my_choices: my_choices.append(choice) random.shuffle(my_choices) answer_idx = my_choices.index(answer) print('Choices:\n') if num: return enumerate(my_choices, start=1), answer_idx else: return my_choices def practice(self, answer): """Prompts user to type the answer 3x if the guess is incorrect within the hard version of the game""" print('Please type the answer 3x, each on its own line.\n') count = 0 while count < 3: word = input('> ').lower() if word == answer: count += 1 else: print('Make sure your spelling is correct.') print('\nExcellent!')
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 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""" x = await self.bot.say("Searching...") search_term = word.split(" ", 1)[0] result = self.dictionary.antonym(search_term) if result is None: await self.bot.delete_message(x) await self.bot.say("This word is not in the dictionary.") return await self.bot.delete_message(x) 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""" x = await self.bot.say("Searching...") search_term = word.split(" ", 1)[0] result = self.dictionary.synonym(search_term) if result is None: await self.bot.delete_message(x) await self.bot.say("This word is not in the dictionary.") return await self.bot.delete_message(x) await self.bot.say("Synonyms for **" + search_term + "**: *" + "*, *".join(result) + "*")
def mainloop(): global loop while loop: query = takeCommand().lower() # chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s' # group of "open" keyword related programmes if 'what' in query: url = search(query, stop=1) try: webbrowser.open(url) except webbrowser.Error: print("unexpected error happened in webbrower") text2.insert(tk.END, "unexpected error happened in webbrower\n") if 'open' in query: if 'open youtube' in query or 'open you tube' in query: webbrowser.open("youtube.com") elif 'open google scholar' in query: webbrowser.open("https://scholar.google.com/") elif 'open google' in query: webbrowser.open("google.com") elif 'open reddit' in query: webbrowser.open("reddit.com") elif 'open google drive' in query: webbrowser.open("drive.google.com") elif 'open facebook' in query: webbrowser.open("www.facebook.com") elif 'open instagram' in query: webbrowser.open("www.instagram.com") elif 'open geeksforgeeks' in query: webbrowser.open("https://www.geeksforgeeks.org") elif 'open stackoverflow' in query: webbrowser.open("stackoverflow.com") elif 'open stack overflow' in query: webbrowser.open("stackoverflow.com") elif 'open codechef' in query: webbrowser.open("www.codechef.com") elif 'open code chef' in query: webbrowser.open("www.codechef.com") elif 'open udemy' in query: webbrowser.open("www.udemy.com") elif 'open learncpp' in query: webbrowser.open("www.learncpp.com") elif 'open learn cpp' in query: webbrowser.open("www.learncpp.com") elif 'open main website' in query: webbrowser.open("www.iitr.ac.in") elif 'open channel i' in query: webbrowser.open("www.channeli.in") elif 'open github' in query or 'open git hub' in query: webbrowser.open("www.github.com") elif 'open twitter' in query: webbrowser.open("www.twitter.com") elif 'open movies' in query: webbrowser.open("yts.lt") elif 'open course' in query: webbrowser.open("www.coursera.org") elif 'open coursera' in query: webbrowser.open("www.coursera.org") elif 'open e library' in query: webbrowser.open("https://ndl.iitkgp.ac.in/") elif 'open photoshop' in query: webbrowser.open("www.photoshop.com") elif 'open glassdoor' in query: webbrowser.open("https://www.glassdoor.co.in/index.htm") elif 'open linkedin' in query: webbrowser.open("https://in.linkedin.com/") elif 'open ted talks' in query: webbrowser.open("https://www.ted.com/#/") elif 'open custom 1' in query: os.startfile(customPaths["custom_path1"]) elif 'open custom 2' in query: os.startfile(customPaths["custom_path2"]) elif 'open custom 3' in query: os.startfile(customPaths["custom_path3"]) elif 'wikipedia' in query: try: speak('Searching Wikipedia...') query = query.replace("wikipedia", "") if "in" in query: query = query.replace("in", "") if "search" in query: query = query.replace("search", "") results = wikipedia.summary(query, sentences=2) speak("According to Wikipedia") print(results) text2.insert(tk.END, results + "\n") speak(results) except: print("sorry, could not find a result") text2.insert(tk.END, "sorry, could not find a result\n") speak("sorry, could not find a result") elif 'activate alpha' in query or 'wolfram alpha' in query or 'wolfram' in query: while True: print('do you want to ask oral question or a math expression?') text2.insert( tk.END, 'do you want to ask oral question or a math expression?\n') speak('do you want to ask oral question or a math expression?') print('speak oral/mathematics/exit') text2.insert(tk.END, 'speak oral/mathematics/exit\n') inp = takeCommand() if 'oral' in inp: speak("ask question") print("ask question: ") text2.insert(tk.END, "ask question: \n") query = takeCommand() elif 'mathematics' in inp: print('Please type the question: ') text2.insert(tk.END, 'Please type the question: \n') query = input() elif 'exit' in inp: break try: res = client.query(query) output = next(res.results).text print(output) speak(output) except StopIteration: print('speak again') text2.insert(tk.END, 'speak again\n') except: print("can't find this in library") text2.insert(tk.END, "can't find this in library\n") inp = '' query = '' elif 'google search' in query: query = query.replace("google search", "") # you have to update this path for your machine for now # chrome_path = r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe %s' for url in search(query, tld="co.in", num=1, stop=1, pause=2): try: webbrowser.open("https://google.com/search?q=%s" % query) except: print("unexpected error happened in webbrower") text2.insert(tk.END, "unexpected error happened in webbrower\n") elif 'meaning of ' in query: query = query.replace("meaning of ", "") dictionary = PyDictionary() try: query = query.replace("what is the meaning of ", "") b = 'here is the meaning of the word' c = b + query speak(c) test_dict = dictionary.meaning(query) res = [ value[i] for key, value in test_dict.items() for i in range(1) ] # shows most relevent meaning print(str(res[0])) text2.insert(tk.END, str(res[0]) + "\n") speak(str(res[0])) except: print("sorry! word not found...") text2.insert(tk.END, "sorry! word not found...\n") elif 'play music' in query: music_dir = customPaths["music_path"] songs = os.listdir(music_dir) y = random.randrange(0, len(songs)) print("Playing " + songs[y]) try: os.startfile(os.path.join(music_dir, songs[y])) except: text2.insert(tk.END, "sorry, the music file cannot be opened\n") elif 'exit code blocks' in query or 'exit codeblocks' in query: os.system("taskkill /f /im codeblocks.exe") elif 'exit' in query: speak("good bye sir, have a nice day") loop = False elif 'time' in query: strTime = datetime.datetime.now().strftime("%H:%M:%S") print("The Time is : " + strTime) speak(f"Sir, the time is {strTime}") elif 'date' in query: print("Present date is : ", end="") print(date.today()) speak(date.today()) elif 'spotify' in query: os.startfile( "C:\\Users\\hp\\AppData\\Roaming\\Spotify\\Spotify.exe") elif 'exit spotify' in query: os.system("taskkill /f /im spotify.exe") elif 'visual studio' in query: os.startfile( "C:\\Users\\hp\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe" ) elif 'code' in query: os.startfile( "C:\\Users\\hp\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe" ) elif 'downloads' in query: os.startfile("C:\\Users\\hp\\Downloads") elif 'download' in query: os.startfile("C:\\Users\\hp\\Downloads") elif 'exit spotify' in query: os.system("taskkill /f /im spotify.exe") elif 'i am bored' in query: speak('maybe this programmer joke could make you smile.') speak(pyjokes.get_joke()) elif 'shut down' in query: os.system("shutdown /s /t 1") elif 'shutdown' in query: print("Do you really want to ShutDown?[y/n]") response = input() if response == 'y': os.system("shutdown /s /t 1")
from PyDictionary import PyDictionary dictionary = PyDictionary() f = open("english3.txt", "r") meanings = open("meaning.txt", "w+") for line in f: # print line, m = str(dictionary.meaning(line)) if m != "None": print(line + " " + m) meanings.write(line + m + "\r\n") meanings.close()
text = text.replace("!", "!<stop>") text = text.replace("<prd>", ".") sentences = text.split("<stop>") sentences = sentences[:-1] sentences = [s.strip() for s in sentences] return sentences dictionary = PyDictionary() story = open("fahren").read() pages = re.split("[\n][\n]\d+[\n][\n]", story) sentences = [split_into_sentences(page) for page in pages] words = open("words").read().split("\n") for word in words: sentence = "" page = 0 for i in range(len(sentences)): for i_sentence in sentences[i]: if word in i_sentence: sentence = i_sentence page = i + 1 definition = dictionary.meaning(word) word_type = "" for i in definition.keys(): word_type = i break if sentence != "": print( f"{word} - {word_type}\n{definition[word_type][0]}.\n\"{sentence}.\"\n Fahrenheit 451, Ray Bradbury pg. {page}" )
from PyDictionary import PyDictionary from random_word import RandomWords r = RandomWords() pd = PyDictionary() # Return a single random word word_of_the_game = r.get_random_word(minLength=3, maxLength=12, hasDictionaryDef="true") print(word_of_the_game) today_word = word_of_the_game print(pd.meaning(word_of_the_game)) # creating a blank space blank_word = [] length = int(len(word_of_the_game)) for i in range(0, length): blank_word.append("_") print(blank_word) counter = 0 while counter < 7: x = input("Enter the letter : ") flag = word_of_the_game.find(x) if flag < 0: counter = counter + 1 else: while flag >= 0: word_of_the_game = word_of_the_game.replace(x, '_', 1) blank_word[flag] = x flag = word_of_the_game.find(x) print(blank_word)
from PyDictionary import PyDictionary dictionary=PyDictionary() features="html.parser" print (dictionary.meaning("")) print (dictionary.synonym("")) print (dictionary.antonym(""))
from PyDictionary import PyDictionary words = ['seid', 'hello', 'peace'] dictionary = PyDictionary(words) print(dictionary.meaning('indentation')) print(dictionary.synonym("life")) print(dictionary.getMeanings()) print(dictionary.getSynonyms())
def processRequest(req): #for wolfram alpha if req.get("result").get("action") == "fact": client = wolframalpha.Client("4393W5-W6E838H957") john = client.query(req.get("result").get("resolvedQuery")) answer = next(john.results).text return { "speech": answer, "displayText": answer, "source": "From wolfram_alpha" } #translator #uses microsoft translator api USE your key here elif req.get("result").get("action") == "tran": translator = Translator( '''jkthaha''', '''syosNIlEOJnlLByQGcMS+AIin0iaNERaQVltQvJS6Jg=''') try: s = translator.translate( req.get("result").get("parameters").get("question"), req.get("result").get("parameters").get("language")) res = makeWebhookResult(s) return res except: res = makeWebhookResult("Server busy, please try again later") return res #for news #takes news randomly from different sources use newsapi docs for more info elif req.get("result").get("action") == "news": y = random.randint(1, 6) if y == 1: r = requests.get( 'https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=1412588264c447da83a7c75f1749d6e8' ) j = r.json() x = j.get('articles') newp = "The headlines are: " + "1. " + x[0][ "title"] + "." + " 2. " + x[1]["title"] + "." + " 3. " + x[2][ "title"] + "." + " 4. " + x[3]["title"] + "." + " 5. " + x[ 4]["title"] + "." res = makeWebhookResult(newp) return res elif y == 2: r = requests.get( 'https://newsapi.org/v1/articles?source=the-times-of-india&sortBy=latest&apiKey=1412588264c447da83a7c75f1749d6e8' ) j = r.json() x = j.get('articles') newp = "The headlines are: " + "1. " + x[0][ "title"] + "." + " 2. " + x[1]["title"] + "." + " 3. " + x[2][ "title"] + "." + " 4. " + x[3]["title"] + "." + " 5. " + x[ 4]["title"] + "." res = makeWebhookResult(newp) return res elif y == 3: r = requests.get( 'https://newsapi.org/v1/articles?source=independent&sortBy=top&apiKey=1412588264c447da83a7c75f1749d6e8' ) j = r.json() x = j.get('articles') newp = "The headlines are: " + "1. " + x[0][ "title"] + "." + " 2. " + x[1]["title"] + "." + " 3. " + x[2][ "title"] + "." + " 4. " + x[3]["title"] + "." + " 5. " + x[ 4]["title"] + "." res = makeWebhookResult(newp) return res elif y == 4: r = requests.get( 'https://newsapi.org/v1/articles?source=bbc-sport&sortBy=top&apiKey=1412588264c447da83a7c75f1749d6e8' ) j = r.json() x = j.get('articles') newp = "The headlines from bbc sports: " + "1. " + x[0][ "title"] + "." + " 2. " + x[1]["title"] + "." + " 3. " + x[2][ "title"] + "." + " 4. " + x[3]["title"] + "." + " 5. " + x[ 4]["title"] + "." res = makeWebhookResult(newp) return res elif y == 5: r = requests.get( 'https://newsapi.org/v1/articles?source=ars-technica&sortBy=latest&apiKey=1412588264c447da83a7c75f1749d6e8' ) j = r.json() x = j.get('articles') newp = "The headlines are: " + "1. " + x[0][ "title"] + "." + " 2. " + x[1]["title"] + "." + " 3. " + x[2][ "title"] + "." + " 4. " + x[3]["title"] + "." + " 5. " + x[ 4]["title"] + "." res = makeWebhookResult(newp) return res elif y == 6: r = requests.get( 'https://newsapi.org/v1/articles?source=the-hindu&sortBy=latest&apiKey=1412588264c447da83a7c75f1749d6e8' ) j = r.json() x = j.get('articles') newp = "The headlines are: " + "1. " + x[0][ "title"] + "." + " 2. " + x[1]["title"] + "." + " 3. " + x[2][ "title"] + "." + " 4. " + x[3]["title"] + "." + " 5. " + x[ 4]["title"] + "." res = makeWebhookResult(newp) return res #for wikipedia elif req.get("result").get("action") == "wiki": param = req.get("result").get("parameters").get("any") fin = wikipedia.summary(param, sentences=2) res = makeWebhookResult(fin) return res #for local time elif req.get("result").get("action") == "time": app_id = "4393W5-W6E838H957" client = wolframalpha.Client(app_id) john = client.query("time in bangalore") answer = next(john.results).text res = makeWebhookResult(answer) return res #for weather (yahoo api) elif req.get("result").get("action") == "yahooWeatherForecast": baseurl = "https://query.yahooapis.com/v1/public/yql?" yql_query = makeYqlQuery(req) if yql_query is None: return {} yql_url = baseurl + urllib.urlencode({'q': yql_query}) + "&format=json" result = urllib.urlopen(yql_url).read() data = json.loads(result) res = makeWebhookResult1(data) return res #for dictionary else: dictionary = PyDictionary() ch = req.get('result').get('parameters').get('word') test = req.get('result').get('parameters').get('dictionary') if test == 'antonym': res = dictionary.antonym(ch) try: try: answer = "Antonym for the word " + ch + " are: {0}, {1}, {2}, {3}, {4}.".format( res[0], res[1], res[2], res[3], res[4]) except: try: answer = "Antonym for the word " + ch + " are: {0}, {1}, {2}, {3}.".format( res[0], res[1], res[2], res[3]) except: try: answer = "Antonym for the word " + ch + " are: {0}, {1}, {2}.".format( res[0], res[1], res[2]) except: answer = "Antonym for the word " + ch + " are: {0}, {1}.".format( res[0], res[1]) except: answer = "There is no antonym for this word" return makeWebhookResult(answer) elif test == 'definition': re1s = dictionary.meaning(ch) try: try: answer = "The word {0} is a verb and its meaning is {1}".format( ch, re1s['Verb']) except: try: answer = "The word {0} is a noun and its meaning is {1}".format( ch, re1s['Noun']) except: answer = "The word {0} is an adjective and its meaning is {1}".format( ch, re1s['Adjective']) except: answer = re1s return makeWebhookResult(answer) elif test == 'synonym': res = dictionary.synonym(ch) try: try: answer = "Synonym for the word " + ch + " are: {0}, {1}, {2}, {3}, {4}.".format( res[0], res[1], res[2], res[3], res[4]) except: try: answer = "Synonym for the word " + ch + " are: {0}, {1}, {2}, {3}.".format( res[0], res[1], res[2], res[3]) except: try: answer = "Synonym for the word " + ch + " are: {0}, {1}, {2}.".format( res[0], res[1], res[2]) except: answer = "Synonym for the word " + ch + " are: {0}, {1}.".format( res[0], res[1]) return makeWebhookResult(answer) except: answer = "There is no Synonym for this word" return makeWebhookResult(answer)
from tinycards import Tinycards from tinycards.model import Deck from PyDictionary import PyDictionary import yaml, json, sys import config dictionary = PyDictionary() tinycards = Tinycards(config.TINY_CARDS_CREDENTIALS['email'], config.TINY_CARDS_CREDENTIALS['password']) deck = Deck('12 Rules Of Life') deck = tinycards.create_deck(deck) fh = open('words.txt') for word in fh: meaning = str(dictionary.meaning(word)) translation_table = dict.fromkeys(map(ord, '{}[]\''), None) meaning = meaning.translate(translation_table) print(meaning) deck.add_card((word, meaning)) fh.close() tinycards.update_deck(deck)
# Splitting at ':' print(word.split(':')) word = 'CatBatSatFatOr' # Splitting at 3 print([word[i:i+3] for i in range(0, len(word), 3)]) word = 'geeks, for, geeks, pawan' # maxsplit: 0 print(word.split(', ', 0)) # maxsplit: 4 print(word.split(', ', 4)) # maxsplit: 1 print(word.split(', ', 1)) """https://pypi.org/project/parse/""" pip install PyDictionary from PyDictionary import PyDictionary dictionary=PyDictionary() print (dictionary.meaning("indentation")) print (dictionary.synonym("Life")) print (dictionary.antonym("Life"))
def lets_chat(self): def listen_below(): r = sr.Recognizer() self.root.ids.top.text = "listening...." self.speak('we are listening') with sr.Microphone() as source: r.energy_threshold = 10000 audio = r.listen(source) try: query = r.recognize_google(audio, language='en-in') print('User: '******'\n') return query except sr.UnknownValueError: self.root.ids.top.text = 'Sorry sir! I didn\'t get that! Try typing the word!' self.speak('Sorry sir! I didn\'t get that! Try typing the word!') s = input() return s query = listen_below() if "meaning" in query: c = query[-1] dictionary = PyDictionary(c) ans = dictionary.meaning(c) if ans: x = ans.keys() y =[] for i in x: y.append(i) z = ans[y[0]][:2] w = ",".join(z) hey = "{}: {}".format(y[0],w) self.speak(hey) else: self.speak("We didnt got you sir") elif "synonym" in query: c = query[-1] dictionary = PyDictionary(c) synonym = list(dictionary.getSynonyms()) d = synonym[0][c][:4] e = ",".join(d) self.root.ids.antosynom.text = e self.speak(e) elif "antononym" in query: c = query[-1] dictionary = PyDictionary(query[-1]) synonym = list(dictionary.getAntonyms()) d = synonym[0][c][:4] e = ",".join(d) self.speak(e) elif "about " in query: self.speak("This A dictionary application which is a listing of words in one or more specific languages, often arranged alphabetically (or by radical and stroke for ideographic languages), which may include information on definitions, usage, etymologies, pronunciations, translation") elif "features" in query: self.speak("This Dictionary application consists of listed features such as pronunciation of an entered word,Translations of word or sentence into four languages that is Spanish,French,German,japenese,antononyms and synonyms of an word , there is also spelling checker as well as grammar checker into this application which corrects a sentence and there is also an AI bot named pam which helps in assisting the user") elif "english" in query: self.speak("English may not be the most spoken language in the world, but it is the official language of 53 countries and spoken by around 400 million people across the globe. Being able to speak English is not just about being able to communicate with native English speakers, it is the most common second language in the world. If you want to speak to someone from another country then the chances are that you will both be speaking English to do this.") elif "created" in query: self.speak("this application is created in using KivyMD is a collection of Material Design compliant widgets for use with Kivy, a framework for cross-platform, touch-enabled graphical applications. The project's goal is to approximate Google's Material Design spec as close as possible without sacrificing ease of use or application performance") elif "gmail" in query: self.speak('okay') webbrowser.open('www.gmail.com') elif 'open hackerrank' in query: self.speak('okay') webbrowser.open('https://www.hackerrank.com') elif 'open interviewbit' in query: self.speak('okay') webbrowser.open('https://www.interviewbit.com/profile') elif 'open leetcode' in query: self.speak('okay') webbrowser.open('https://leetcode.com') elif 'open chrome' in query: self.speak('okay') webbrowser.open('www.google.com') elif 'open github' in query: self.speak('okay') webbrowser.open('https://github.com') else: query = query self.speak('Searching...') try: results = wikipedia.summary(query, sentences=2) self.speak('Got it.') self.speak('WIKIPEDIA says - ') self.speak(results) except: webbrowser.open('www.google.com')
from PyDictionary import PyDictionary import json dictionary=PyDictionary() lines_list = open('vocab', 'r').read().splitlines() dicdic={} undefs = [] for s in lines_list: word = str(s.upper()) definition = str(dictionary.meaning(s)) if definition == "None": undefs.append(word) else: dicdic[word] = definition json.dump(dicdic, open("definitions.txt",'w')) print (undefs)
from PyDictionary import PyDictionary dictionary = PyDictionary() import pyttsx engine = pyttsx.init() engine.setProperty('rate', 150) variable = "" while variable != 'quit': variable = raw_input('Lookup a word, type something in: ') meaning = (dictionary.meaning(variable)) synonym = (dictionary.synonym(variable)) antonym = (dictionary.antonym(variable)) translate = (dictionary.translate(variable, 'es')) google = (dictionary.googlemeaning(variable)) print("meaning :", meaning) print('\n') print("synonym :", synonym) print('\n') print("antonym :", antonym) print('\n') print("translated to spanish :", translate) print('\n') print("google meaning: ", google) engine.say('google meaning is ') engine.say(google) engine.runAndWait()
# you have to update this path for your machine for now #chrome_path = r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe %s' for url in search(query, tld="co.in", num=1, stop = 1, pause = 2): try: webbrowser.open("https://google.com/search?q=%s" % query) except webbrowser.Error: print("unexpected error happened in webbrower") elif 'meaning of ' in query: query=query.replace("meaning of ","") dictionary=PyDictionary() try: query=query.replace("what is the meaning of ","") b='here is the meaning of the word' c=b+query speak(c) test_dict=dictionary.meaning(query) res = [ value[i] for key,value in test_dict.items() for i in range(1)] print (str(res[0])) # shows most relevent meaning speak(str(res[0])) except: print("sorry! word not found...") elif 'play music' in query: music_dir = 'F:\\Music' songs = os.listdir(music_dir) y=random.randrange(0,50,1) print(songs[y]) os.startfile(os.path.join(music_dir, songs[y])) elif'exit code blocks' in query or 'exit codeblocks' in query: os.system("taskkill /f /im codeblocks.exe")
def output(request): # Validation of form if request.method == "POST": # Validation of request if 'inputURL' in request.POST: # Validation of image url imageURL = request.POST.get('inputURL') image_output = imageURL indexOfDot = imageURL.rfind(".") if indexOfDot == -1: return fail(request) # not an image URL indexOfDot += 1 extension = imageURL[indexOfDot:] if extension != 'jpg' and extension != 'jpeg' and extension != 'png': return fail(request) # not a valid image (jpg, jpeg, png) client_id = '8SkASX_SM8xc-fxMF4SdpzS_b9uew8yG0UrQp0y6' secret_id = 'EXkfCNxXeiHtnpsxn9Njui_yUpCuvcSAXzfSYjwN' clarifai_api = ClarifaiApi(client_id, secret_id) # assumes environment variables are set. return output(request, makes{image_output:'image_output', text_output:'text_output'}) result = clarifai_api.tag_image_urls(imageURL) except ApiError: #return fail(request) messages.add_message(request, messages.INFO, "ApiError") return HttpResponseRedirect('makestory/fail.html') class_list = result['results'][0]['result']['tag']['classes'] prob_list = result['results'][0]['result']['tag']['probs'] class_str = "" for i in range(0, len(class_list)): class_str += class_list[i] + " " # currently just the list of matched words text_output = class_list.__str__() # Parts of speech recognition tokens = nltk.word_tokenize(class_str) dictionary = PyDictionary() nouns = [] verbs = [] adjectives = [] otherPos = [] for word in tokens: definition = dictionary.meaning(word) # https://pypi.python.org/pypi/PyDictionary/1.3.4 assignment = definition.keys()[0] # Get the part of speech from the dictonary # assignment = tuple[1] if assignment == 'Noun': nouns.append(word) elif assignment == 'Verb': verbs.append(word) elif assignment == 'Adjective': adjectives.append(word) else: otherPos.append(word) # Create the grammar #P:prepositions, DET:articles, adverbs P = ["on","in","at","since","for","ago","before","to","past","to","until","by","in","at","on","under","below","over","above","into","from","of","on","at"] DET = ["the","a","one","some","few","a few","the few","some"] assignments = pos_tag(tokens) # tagset='universal' for ADJ, NOUN, etc. pos_tags = [] pos_words = {} for tuple in assignments: word = tuple[0] pos = tuple[1] if pos in pos_words: pos_words[pos].append(word) else: pos_words[pos] = [] pos_tags.append(pos) grammar = """ S -> NP VP PP -> P NP NP -> Det N | Det N PP VP -> V NP | VP PP Det -> 'DT' """ # N -> 'NN' # V -> 'VBZ' # P -> 'PP' # adverb is RB if 'NN' in pos_words: grammar += 'N ->' + ' | '.join(pos_words['NN']) + '\n' if 'VB' in pos_words: grammar += 'V ->' + ' | '.join(pos_words['VB']) + '\n' if 'JJ' in pos_words: grammar += 'A ->' + ' | '.join(pos_words['JJ']) + '\n' simple_grammar = CFG.fromstring(grammar) #simple_grammar.start() simple_grammar.productions() sentences = [] for sentence in generate(simple_grammar, n=10): sentences.append(' '.join(sentence)) # parser = nltk.ChartParser(simple_grammar) # tree = parser.parse(pos_tags) caption = 'this is a caption' story = 'this is the story' return render(request, 'makestory/output.html', { 'nouns_output': nouns, 'verbs_output': verbs, 'adjectives_output': adjectives, 'otherPos_output': otherPos, 'imageURL_output': imageURL, 'caption_output': caption, 'story_output': story, 'sentences_test_output': sentences, } )
from PyDictionary import PyDictionary import pprint # creating a dictionary instance dict = PyDictionary() # taking input from the user: the word and letter for specified action needed by the user word = input("Please enter a word: ") action = input( """\nWhat do you want to find? a. meaning b. synonyms c. antonyms. Please enter a letter: """) # performing specified action needed based on user input if action == 'a' or action == 'A': meaning = dict.meaning(word) print("\nThe meaning of the word " + word.upper() + "\n\n") pprint.pprint(meaning) elif action == 'b' or action == 'B': synonymns = dict.synonym(word) print("\nSynonymns for the word " + word.upper() + "\n\n") pprint.pprint(synonymns) elif action == 'c' or action == 'C': antonyms = dict.antonym(word) print("\nAntonyms for the word " + word.upper() + "\n\n") pprint.pprint(antonyms)
def get_meaning(name): dictionary = PyDictionary() value = dictionary.meaning(name) if value is None: return json.dumps({'error': 'Word has no meaning in API'}) return value
async def define(self, word: str): dictionary = PyDictionary() await self.bot.say(dictionary.meaning(word))