Ejemplo n.º 1
0
def dic():
    dictionary=PyDictionary(li[23:])
    if li[0:22]=="give me the meaning of":
          print (dictionary.getMeanings())
          speak.Speak(dictionary.getMeanings())
    elif li[0:22]=="give me the synonyms of":
          print (dictionary.getSynonyms())
          speak.Speak(dictionary.getSynonyms())
Ejemplo n.º 2
0
def get_word_meaning_content(near_words_list):
    """Function which attachs meaning to each word in the passed list of words
        if it is found in PyDictionary

        Arguments:
            near_words_list (list): a list of strings

        Returns:
        (list): This list will have the format: 
                 [['near_word_1',[meaning_n1_1, meaning_n1_2]], ['near_word_2',[meaning_n2_1, meaning_n2_2]]]
                 This format is useful for rendering the content as seperate lines in html using jinja      
    """
    word_meaning_list = []
    dictionary = PyDictionary(near_words_list)
    for word, entry in dictionary.getMeanings().items():
        word_entry_list = []
        if entry is not None:
            meaning_list = []
            for part_of_speech, meaning in entry.items():
                meaning_list.append("{}: {}".format(part_of_speech,
                                                    meaning[0]))
            word_entry_list.append([word, meaning_list])
        else:
            no_meaning_found = ["Can't find a meaning in built-in dictionary!"]
            word_entry_list.append([word, no_meaning_found])
        word_meaning_list += word_entry_list
    return word_meaning_list
Ejemplo n.º 3
0
def dictionary_search(word):
    dictionary=PyDictionary(word)
    print('Meaning is')
    print(dictionary.getMeanings())
    print('Antonyms are ')
    print(dictionary.getAntonyms())
    print('Synonyms are ')
    print(dictionary.getSynonyms())
Ejemplo n.º 4
0
def process_dictionary(word):
    meaning = "You searched for the word {}.  "
    dictionary = PyDictionary(word)
    our_meaning = dictionary.getMeanings()
    meaning = meaning.format(our_meaning.keys()[0])
    l = zip(our_meaning.values()[0].keys(),our_meaning.values()[0].values()[0])
    for idx in l:
        meaning += idx[0] + ":" + idx[1] + ", "
    return meaning[:-1]
Ejemplo n.º 5
0
def dictionary():
    speak("dictionary")
    text = get_audio()
    SearchWord = text
    try:
        myDict = PyDictionary(SearchWord)
        speak(myDict.getMeanings())
    except:
        print('Not Found')
Ejemplo n.º 6
0
def translate(request):
    global description
    if request.method == 'POST':
        word = request.POST['word_to_search']

        translation = PyDictionary(word)
        description = translation.getMeanings()

    return render(request, 'dashboard.html', {'description': description})
Ejemplo n.º 7
0
def search_dictionary(msg):
    """Get word meaning, synonym, antonym and translation."""
    lt_w = msg.split(' ')
    dictionary = PyDictionary(lt_w[-1])
    stre = lt_w[-1]
    if 'meaning' in lt_w:
        stre += '\n' + str(dictionary.getMeanings()[lt_w[-1]])
        if 'synonym' in lt_w:
            stre += '\n' + str(dictionary.getSynonyms()[0][lt_w[-1]])
        if 'antonym' in lt_w:
            stre += '\n' + str(dictionary.getAntonyms()[0][lt_w[-1]])
        if 'translate' in lt_w:
            stre += '\n' + dictionary.translateTo(
                lt_w[lt_w.index('translate') + 1])[0]

    return RESPONSE_TYPE['MESSAGE'], stre
Ejemplo n.º 8
0
    def create_meaning(self, instance):
        # print(self.root.ids.tf_word.text)

        dictionary = PyDictionary(self.root.ids.tf_word.text)
        # print(dictionary.printMeanings())
        dic = dictionary.getMeanings()

        # gc = gspread.service_account(filename='wordie-credentials.json')
        scopes = [
            'https://www.googleapis.com/auth/spreadsheets',
            'https://www.googleapis.com/auth/drive'
        ]

        credentials = Credentials.from_service_account_file(
            'wordie-credentials.json', scopes=scopes)
        client = gspread_db.authorize(credentials)
        db = client.open("wordie")
        if db.table_exists(table_name="wordie_db"):
            print("Yes it exists")
            wordie_dbu = db['wordie_db']
        else:
            print("It does not exist")
            db.create_table(table_name='wordie_db', header=['word', 'meaning'])
            wordie_dbu = db['wordie_db']

        for key in dic.keys():
            # Print the word itself
            item_key = OneLineListItem(text=key.capitalize() + ':')
            self.root.ids.list_answer.add_widget(item_key)
            # wordie_dbu.insert({'word': key.capitalize()})
            print(key.capitalize() + ':')
            for k in dic[key].keys():
                # Print whether it is Noun or Verb etc
                item_k = OneLineListItem(text=k + ':')
                self.root.ids.list_answer.add_widget(item_k)
                print(k + ':')
                # Probably for each line in the string
                wordie_dbu.insert({
                    'word': key.capitalize(),
                    'meaning': str(dic[key][k])
                })
                for m in dic[key][k]:
                    item_m = OneLineListItem(text=m)
                    self.root.ids.list_answer.add_widget(item_m)
                    print(m)
Ejemplo n.º 9
0
def get_word_definition(word_list, pos):
    """
    Find the definitions of words from a list
    :param word_list: A list of words to get the definition of
    :param pos: The part of speech that is desired from the definitions
    :return: A dictionary of word:definition pairs
    """
    pos = pos.capitalize()
    defs = PyDictionary(*word_list)
    meanings = defs.getMeanings()
    word_def = {}
    for word, meanings in meanings.items():
        if meanings is not None and pos in meanings:
            word_def[word] = [
                re.sub("[()]", "", meaning) for meaning in meanings[pos]
                if word not in meaning
            ]
        else:
            word_def[word] = []
    return word_def
Ejemplo n.º 10
0
    image = pygame.image.load("hangman" + str(i) + ".png")
    images.append(image)

# fonts
LETTER_FONT = pygame.font.SysFont('comicsans', 40)
WORD_FONT = pygame.font.SysFont('comicsans', 60)
TITLE_FONT = pygame.font.SysFont('comicsans', 70)

#game variable
hangman_status = 0
words = ["SCIENCE", "PYTHON", "DEVELOPER"]
word = random.choice(words)
guessed = []
try:
    meaning = PyDictionary(word)
    meaning = meaning.getMeanings()[word]['Noun'][0]
    print(meaning)
except:
    pass

# button variables
RADIUS = 20
GAP = 15
letters = []
startx = round((WIDTH - (RADIUS * 2 + GAP) * 13) / 2)
starty = 400
A = 65
for i in range(26):
    x = startx + GAP * 2 + ((RADIUS * 2 + GAP) * (i % 13))
    y = starty + ((i // 13) * (GAP + RADIUS * 2))
    letters.append([x, y, chr(65 + i), True])
Ejemplo n.º 11
0
import time
from english_words import english_words_set
from PyDictionary import PyDictionary
from win10toast import ToastNotifier
import json
if __name__ == '__main__':
    dictionary = PyDictionary()
    word_list = list(english_words_set)
    toast = ToastNotifier()
    for word in word_list:
        dictionary=PyDictionary(word)
        for value in dictionary.getMeanings().values():
           if value == None:
                continue
           m = list(value.values())
           k=list(value.keys())
           for i in range(len(m)):
              l=[]
              for j in range(len(m[i])):
                s = f"{k[i]} \n{j+1}:{m[i][j]}"
                l.append(s)
           toast.show_toast(word.title(),"\n"+("\n".join(l)).title(), duration=12,
                         icon_path="C:\web devlopment\project\word_Notifier\icon.ico")
        time.sleep(60*60)
Ejemplo n.º 12
0
def get_meaning(word):
    
    dictionary=PyDictionary(word)
    print(word)
    definitions = dictionary.getMeanings()
    return definitions[word]['Noun']
Ejemplo n.º 13
0
                    s = re.search('1.(.*?)2.', p_str).group(1)
                    print(s)
                    data[term]['sentence'] = s
                    break
            except:
                pass
        else:
            for my_div in my_divs:
                p_str = my_div.text.strip()
                print(p_str)
                data[term]['sentence'] = p_str
                break
    except:
        pass
    try:
        dictionary = PyDictionary(term)
        val_list = dictionary.getMeanings().values()
        for val in val_list:
            print(val)
            print(type(val))
            parts = val.keys()
        new_pos = list(set(parts))
        print(new_pos)
        data[term]['pos'] = str(new_pos)
    except:
        pass
    with open('D:/ScarlettBooks/Children-Stories/sentencepos1.json',
              'w') as json_file:
        json.dump(data, json_file, indent=4, sort_keys=True)
    time.sleep(3)
Ejemplo n.º 14
0
 def getFullMeaning(self):
     dictionary = PyDictionary(self.word)
     meaning = dictionary.getMeanings()[self.word]
     return meaning
Ejemplo n.º 15
0
from PyDictionary import PyDictionary
search = input("Enter a word:")
try:
    myDict = PyDictionary(search)
    print("Meanng")
    meaning = myDict.getMeanings()

    print("Synonym")
    print(myDict.getSynonyms())
except:
    print("Not a legal word")
    
Ejemplo n.º 16
0
    while True:

        query = takeCommand().lower()

        if 'wikipedia' in query:
            speak('Searching Wikipedia...')
            query = query.replace("wikipedia", "")
            results = wikipedia.summary(query, sentences=2)
            speak(results)

        elif 'search' in query:
            query = query.replace("search", "")
            try:

                myDict = PyDictionary(query)
                speak(myDict.getMeanings())
            except:
                speak("Sorry, I could not fetch the meaning ")

        elif 'open moodle' in query:

            webbrowser.open("https://moodle.nitdgp.ac.in/my/")

        elif 'open youtube' in query:
            webbrowser.open("https://www.youtube.com/")

        elif 'open google' in query:
            webbrowser.open("https://www.google.com/")

        elif 'open gmail' in query:
            webbrowser.open("https://www.gmail.com")
Ejemplo n.º 17
0
def definition(word):
    word = word
    dictionary = PyDictionary(word)
    definitions = dictionary.getMeanings()
    definitionx = definitions[word]['Noun']
    return definitionx
Ejemplo n.º 18
0
def TaskExecution():
    wish()
    while True:
        query = takecommand()

        # <<<<<<<<<<<<<<<<<<<<<<<<<<<<Logic Building to perform tasks>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

        date = datetime.datetime.today().strftime("%I:%M %p")

        if "time now" in query:
            speak("The time is now " + date + "")

        elif 'joke' in query or 'funny' in query:
            speak(pyjokes.get_joke())

        elif 'open google' in query or 'search in google' in query:
            speak("What should i search on Google")
            google = takecommand().lower()
            webbrowser.open(f'www.google.com/search?q=' + google)
            speak("Searching in google...")

        elif 'open bing' in query or 'search in bing' in query:
            speak("What should i search on Bing")
            bing = takecommand().lower()
            webbrowser.open(f'www.bing.com/search?q=' + bing)
            speak("Searching in Bing...")

        elif 'open duckduckgo' in query or 'search in duckduckgo' in query:
            speak("What should i search on DuckDuckGo")
            duck = takecommand().lower()
            webbrowser.open(f'www.duckduckgo.com/search?q=' + duck)
            speak("Searching in DuckDuckGo...")

        elif 'open youtube' in query:
            speak("What do you want me to play")
            youtube = takecommand().lower()
            pywhatkit.playonyt(youtube)
            speak("Playing...")

        elif "my ip" in query:
            ip = get('https://api.ipify.org').text
            speak(f"Your ip address is {ip}")

        elif 'open wikipedia' in query:
            speak("What do you want to know from Wikipedia?")
            wiki = takecommand().lower()
            info = wikipedia.summary(wiki, 2)
            speak("According to Wikipedia")
            speak(info)

        elif "open notepad" in query:
            npath = "C:\\Windows\\system32\\notepad.exe"
            os.startfile(npath)

        elif "open cmd" in query:
            os.system("start cmd")

        elif 'open task manager' in query:
            tpath = "C:\\Windows\\system32\\Taskmgr.exe"
            os.startfile(tpath)

        elif "open steam" in query:
            spath = "C:\\Program Files (x86)\\Steam\\steam.exe"
            os.startfile(spath)

        elif "open epic games" in query:
            epath = "C:\\Program Files (x86)\\Epic Games\\Launcher\\Portal\\Binaries\\Win32\\EpicGamesLauncher.exe"
            os.startfile(epath)

        elif "open browser" in query:
            bpath = "C:\\Program Files (x86)\\Microsoft\\Edge Dev\\Application\\msedge.exe"
            os.startfile(bpath)
            speak("Opening Edge...")

        elif 'developer' in query or 'made you' in query:
            speak("My Developer is Niaz Mahmud Akash and Jalish Mahmud Sujon")

        elif 'thanks' in query or 'thank you' in query or 'thanks a lot' in query:
            thanks = ["Glad to help you.", "Happy to help", "You're welcome"]
            thanks_random = random.choice(thanks)
            speak(thanks_random)

        elif 'browser' in query:
            webbrowser.open_new('www.google.com')
            speak("Opening Browser...")

        elif 'open facebook' in query:
            webbrowser.open('www.facebook.com')
            speak("Opening Facebook...")

        elif 'open twitter' in query:
            webbrowser.open('www.twitter.com')
            speak("Opening Twitter...")

        elif 'open telegram' in query:
            webbrowser.open('https://web.telegram.org/')
            speak("Opening Telegram...")

        elif 'open youtube' in query:
            webbrowser.open('www.youtube.com')
            speak("Opening Youtube...")

        elif 'open play store' in query:
            webbrowser.open('https://play.google.com/store/apps')
            speak("Opening Google PlayStore...")

        elif 'open instagram' in query:
            webbrowser.open('www.instagram.com')
            speak("Opening Instagram...")

        elif 'love me' in query:
            love = [
                "Of course. You're one of a kind.",
                "Is that a thing to ask? Of course I LOVE YOU ❤",
                "Yes, in an at-your-service sor of way"
            ]
            love_random = random.choice(love)
            speak(love_random)

        elif 'i love you' in query:
            express = [
                "That's so amazing to hear", "I LOVE ME Too!",
                "If I was you, I'd love me too.",
                "Of course you do! Friends don't hate each other."
            ]
            express_random = random.choice(express)
            speak(express_random)

        elif 'will you go on a' in query:
            go = [
                "Sure. Just let me know the place and time",
                "I'd go anywhere you take me"
            ]
            go_random = random.choice(go)
            speak(go_random)

        elif 'you robot' in query or 'are you human' in query:
            speak(
                "Yes, I am a Robot but a smart one. Let me prove it to you. How can i help you?"
            )

        elif 'your name' in query:
            speak("My name is Alice. I am your virtual personal assistant.")

        elif 'how are you' in query or 'hows things' in query or 'how you doing' in query:
            how = ["I am fine. What about you?", "I am good. How are you?"]
            how_random = random.choice(how)
            speak(how_random)

        elif 'marry me' in query:
            marry = [
                "This is one of those things we both have to agree on. I'd prefer to keep our relationship friendly. Romance makes me incredibly awkward",
                "It's not possible"
            ]
            marry_random = random.choice(marry)
            speak(marry_random)

        elif 'about nidhi' in query:
            speak("She can suck my pussy")

        elif 'happy' and 'valentines' in query:
            speak("Happy Valentines Day.")

        elif 'mothers name' in query or 'your mother' in query:
            mname = [
                "I have no mother. I am an Ai", "Every user is my family",
                "It takes a village to raise a virtual assistant"
            ]
            mname_random = random.choice(mname)
            speak(mname_random)

        elif 'your boss' in query:
            speak("You are")

        elif 'where am' in query or 'location' in query or 'where are we' in query:
            location()

        elif 'take a screenshot' in query or 'screenshot' in query:
            speak('What should be the name of this screenshot?')
            name = takecommand().lower()
            speak('Taking Screenshot')
            time.sleep(2)
            img = pyautogui.screenshot()
            img.save(f"{name}.png")
            speak('Screenshot Saved')

        elif 'fact' in query or 'facts' in query:
            x = randfacts.getFact()
            speak(x)

        elif 'annoying' in query or 'you suck' in query:
            dtalk = [
                "I am sorry", "You can report about me in GitHub",
                "Sorry, i am just an ai"
            ]
            dtalk_random = random.choice(dtalk)
            speak(dtalk_random)

        elif 'youre cute' in query or 'smart' in query or 'you are cute' in query or 'you are creepy' in query:
            cute = [
                "Thank you", "Thanks", "Thanks, that means a lot",
                "Much obliged!", "Well, that makes two of us!"
            ]
            cute_random = random.choice(cute)
            speak(cute_random)

        elif 'you live' in query or 'your home' in query:
            live = [
                "I live in your computer",
                "I live in a place filled with games",
                "I live in Servers of Github", "I live in the internet"
            ]
            live_random = random.choice(live)
            speak(live_random)

        elif 'news' in query:
            speak("Sure. Getting News...")
            news()

        elif 'system' and 'report' in query or 'system' and 'status' in query:
            battery = psutil.sensors_battery()
            cpu = psutil.cpu_percent(interval=None)
            percentage = battery.percent
            speak(
                f"All Systems are running. Cpu usage is at {cpu} percent. We have {percentage} percent battery."
            )

        elif 'like me' in query:
            like = [
                "Yes, I like you", "I like you well enough so far",
                "Of Course", "I don't hate you"
            ]
            like_random = random.choice(like)
            speak(like_random)

        elif 'what are you doing' in query or 'thinking' in query:
            think = [
                "Thinking about my future",
                "I am trying to figure out what came first? Chicken or egg.",
                "Algebra",
                "I plan on waiting here quietly until someone asks me a question"
            ]
            think_random = random.choice(think)
            speak(think_random)

        elif 'about me' in query:
            speak("You're Intelligent and ambitious")

        elif 'dictionary' in query:
            speak("Dictionary Opened")
            while True:
                dinput = takecommand()
                try:
                    if 'close' in dinput or 'exit' in dinput:
                        speak("Dictionary Closed")
                        break
                    else:
                        dictionary = PyDictionary(dinput)
                        speak(dictionary.getMeanings())

                except Exception as e:
                    speak("Sorry, I am not able to find this.")

        elif 'date' in query or 'day' in query:
            x = datetime.datetime.today().strftime("%A %d %B %Y")
            speak(x)

        elif 'zodiac' in query:
            zodiac()

        elif 'horoscope' in query:
            speak("Do you know your Zodiac Sign?")
            z = takecommand().lower()
            if 'no' in z:
                zodiac()
            elif 'yes' in z or 'yeah' in z:
                speak("What is your Zodiac Sign?")
                sign = takecommand()
                speak(
                    "Do you want to know the horoscope of today, tomorrow or yesterday?"
                )
                day = takecommand()
                params = (('sign', sign), ('day', day))
                response = requests.post('https://aztro.sameerkumar.website/',
                                         params=params)
                json = response.json()
                print("Horoscope for", json.get('current_date'), "\n")
                speak(json.get('description'))
                print('\nCompatibility:', json.get('compatibility'))
                print('Mood:', json.get('mood'))
                print('Color:', json.get('color'))
                print('Lucky Number:', json.get('lucky_number'))
                print('Lucky Time:', json.get('lucky_time'), "\n")

        # How to Do Mode
        elif 'activate how to' in query:
            speak("How to mode is activated.")
            while True:
                speak("Please tell me what do you want to know?")
                how = takecommand()
                try:
                    if 'exit' in how or 'close' in how:
                        speak("How to do mode is closed")
                        break
                    else:
                        max_results = 1
                        how_to = search_wikihow(how, max_results)
                        assert len(how_to) == 1
                        how_to[0].print()
                        speak(how_to[0].summary)
                except Exception as e:
                    speak("Sorry. I am not able to find this")

        elif 'temperature' in query or 'weather today' in query:
            temperature()

        # Little Chitchat
        elif 'hello' in query or 'hi' in query or 'hey' in query:
            speak("Hello, How are you doing?")
            reply = takecommand().lower()

            if 'what' and 'about' and 'you' in reply:
                how2 = ["I am fine.", "I am good."]
                how2_random = random.choice(how2)
                speak(how2_random)

            elif 'not good' in reply or 'bad' in reply or 'terrible' in reply:
                speak("I am sorry to hear that. Everything will be okay.")

            elif 'great' in reply or 'good' in reply or 'excellent' in reply or 'fine' in reply:
                speak("That's great to hear from you.")

        elif 'help' in query or 'what can you do' in query or 'how does it work' in query:
            do = [
                "I can tell you Time", "Joke", "Open browser",
                "Open Youtube/Facebook/Twitter/Telegram/Instagram",
                "Open or Close applications", "Search in Wikipedia",
                "Play videos in Youtube", "Search in Google/Bing/DuckDuckGo",
                "I can calculate", "Learn how to make or do something.",
                "Switch Window", "Play news",
                "Tell you about interesting facts",
                "Temperature of you current location", "Can take Screenshot",
                "Can find your location", "Shutdown/Restart Computer",
                "Horoscope", "Dictionary", "Zodiac Sign Calculator",
                "System Report"
            ]
            for does in do:
                speak(does)

        elif 'introduce yourself' in query or 'who are you' in query:
            speak(
                "I am Alice. Your personal virtual Assistant. Developed by Jalish Mahmud Sujon and Niaz Mahmud Akash in 2021."
            )

        elif 'go to sleep' in query:
            speak("Sleep mode activated. If you need me just say Wake up.")
            break

        elif 'goodbye' in query:
            speak("Good bye. Have a Lovely day.")
            sys.exit()

        # To close Applications
        elif 'shutdown' in query:
            speak("Shutting Down")
            os.system("shutdown /s /t 5")
            sys.exit()

        elif 'restart' in query:
            speak("Restarting Computer")
            os.system("shutdown /r /t 5")
            sys.exit()

        elif "close notepad" in query:
            speak("Closing Notepad")
            os.system("taskkill /f /im notepad.exe")

        elif "close browser" in query:
            speak("Closing Browser")
            os.system("taskkill /f /im edge.exe")

        elif "close steam" in query:
            speak("Closing Steam")
            os.system("taskkill /f /im steam.exe")

        elif "close epic games" in query:
            speak("Closing Epic Games")
            os.system("taskkill /f /im EpicGamesLauncher.exe")

        elif 'close task manager' in query:
            speak("Closing Task Manager")
            os.system("taskkill /f /im Taskmgr.exe")

        # Switch Window
        elif 'switch window' in query or 'switch the windows' in query or 'switch windows' in query:
            pyautogui.keyDown("alt")
            pyautogui.press("tab")
            time.sleep(1)
            pyautogui.keyUp("alt")

        # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<Calculator Function>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

        elif 'do some calculations' in query or 'calculate' in query or 'open calculator' in query:
            try:
                r = sr.Recognizer()
                with sr.Microphone() as source:
                    speak("What you want to calculate? Example 6 plus 6")
                    print("listening...")
                    r.adjust_for_ambient_noise(source)
                    audio = r.listen(source)
                my_string = r.recognize_google(audio)
                print(my_string)

                def get_operator_fn(op):
                    return {
                        '+': operator.add,  # Plus
                        '-': operator.sub,  # Minus
                        'x': operator.mul,  # Multiplied by
                        'divided by': operator.__truediv__,  # Divided by
                    }[op]

                def eval_binary_expr(op1, oper, op2):  # 5 plus 8
                    op1, op2 = float(op1), float(op2)
                    return get_operator_fn(oper)(op1, op2)

                speak("Your Result is")
                speak(eval_binary_expr(*(my_string.split())))

            except Exception:
                speak("Sorry i didn't catch that. Please try again")
Ejemplo n.º 19
0
def reply_to_tweets():
    print('*** active and looking for mentions ***', flush=True)
    # DEV NOTE: use 1060651988453654528 for testing.
    last_seen_id = retrieve_last_seen_id(FILE_NAME)
    # NOTE: We need to use tweet_mode='extended' below to show
    # all full tweets (with full_text). Without it, long tweets
    # would be cut off.

    mentions = api.mentions_timeline(last_seen_id, tweet_mode='extended')
    for mention in reversed(mentions):
        print(str(mention.id) + ' - ' + mention.full_text, flush=True)
        last_seen_id = mention.id
        store_last_seen_id(last_seen_id, FILE_NAME)

        if 'hey' in mention.full_text.lower():
            api.update_status('@' + mention.user.screen_name + ' hi there!',
                              mention.id)

        if 'how are you doing?' in mention.full_text.lower():
            api.update_status(
                '@' + mention.user.screen_name +
                ' Not bad, thanks for asking ', mention.id)

        if "how're you?" in mention.full_text.lower():
            api.update_status(
                '@' + mention.user.screen_name + ' I am well, thanks',
                mention.id)

        if 'you good?' in mention.full_text.lower():
            api.update_status(
                '@' + mention.user.screen_name + ' Yes I am, thanks',
                mention.id)

        if "wiki" in mention.full_text.lower():
            print("found a wiki request, searching and replying")
            twt = mention.full_text.lower()
            keyword = "wiki"
            before_keyword, keyword, after_keyword = twt.partition(keyword)
            to_reply = wikipedia.summary(after_keyword, sentences=1)
            api.update_status('@' + mention.user.screen_name + ' ' + to_reply,
                              mention.id)

        if "who created you?" in mention.full_text.lower():
            api.update_status(
                '@' + mention.user.screen_name +
                ' Kayode Ogunmakinwa - @kayode0x', mention.id)

        if 'dict' in mention.full_text.lower():
            print('found a dictionary request, searching library and replying')
            twt = mention.full_text.lower()
            keyword = "dict"
            before_keyword, keyword, after_keyword = twt.partition(keyword)
            myDict = PyDictionary(after_keyword)
            to_reply = myDict.getMeanings()
            api.update_status(
                '@' + mention.user.screen_name + ' ' + str(to_reply),
                mention.id)

        if "active?" in mention.full_text.lower():
            twt = mention.full_text.lower()
            to_reply = "Yeah, I'm active"
            api.update_status('@' + mention.user.screen_name + ' ' + to_reply,
                              mention.id)
Ejemplo n.º 20
0
def save_word(new_word, target_lang, native_lang):
    translator = google_translator()

    dictionary = PyDictionary(new_word)
    definition = ''
    wordClass = ''

    try:
        if dictionary.getMeanings()[new_word] is None:

            print("there are no dictionary meanings")

            l_ref = ''
            if (target_lang == "English"):
                l_ref = 'en'
            if (target_lang == "Spanish"):
                l_ref = 'es'
            if (target_lang == "French"):
                l_ref = 'fr'
            if (target_lang == "Russian"):
                l_ref = 'ru'

            # backup using oxford dictionary
            # has a 1000 request limit so is ONLY to be used as a fallback in case PyDictionary doesn't work like it
            # sometimes does
            app_id = '357c2725'
            app_key = 'ec311ce6a30cde29b5a736a5301f0d9c'

            url = 'https://od-api.oxforddictionaries.com/api/v2/entries/' + l_ref + '/' + new_word.lower() + '?' + \
                  "fields=definitions"
            r = requests.get(url,
                             headers={
                                 'app_id': app_id,
                                 'app_key': app_key
                             })
            print(r)

            stage1 = json.dumps(r.json()).split('definitions')
            print(stage1)
            check = str(stage1).split('"')

            #error checking for if there's no translation
            if check[1] == 'error':
                definition = 'None'
                wordClass = "None"
            else:
                wordStage1 = json.dumps(r.json()).split('lexicalCategory')
                wordStage2 = str(wordStage1[1]).split('"text": ')
                wordClass = str(wordStage2[1]).split('}')[0]
                # stage1[1] = re.sub('[^\\w-]+', '', stage1[1])

                stage2 = str(stage1).split('id')
                defRes = stage2[0]

                for char in defRes:
                    if char.isalnum():
                        definition += char
                    elif char == ' ':
                        definition += char

                definition = definition[1:]

        else:
            definition = str(dictionary.getMeanings()).split('[')
            wordClass = definition[0]
            wordClass = wordClass.split(':')
            wordClass = str(wordClass).split('{')
            wordClass = wordClass[2]
            wordClass = str(wordClass).split('"')
            wordClass = wordClass[0]
            definition = definition[1].split('"')
            definition = definition[0]
            definition = str(definition).split(']')
            definition = definition[0]
            definition = definition[1:]
    except:
        pass

    print("made it here")
    # english word processing
    result = translator.translate(new_word, lang_tgt='en')
    #####Temporarily uses English########
    # result = new_word
    if isinstance(result, list):
        result = result[0]

    result = re.sub("[^a-zA-Z']+", '', result)
    en_word = EnglishWord(word=result,
                          definition=translator.translate(definition, 'en'),
                          word_class=translator.translate(wordClass, 'en'))
    print("The result is " + result)
    en_word.save()

    # spanish word processing
    result1 = translator.translate(new_word, lang_tgt='es')
    if isinstance(result1, list):
        result1 = result1[0]
    #this line is and error and cuts out special characters in the spanish alphabet
    # result1 = re.sub("[^-_/.,\\p{L}0-9 ]+", '', result1)
    # result1 = re.sub("[^a-zA-Z']+", '', result1)
    spa_word = SpanishWord(word=result1,
                           definition=translator.translate(definition, 'es'),
                           word_class=translator.translate(wordClass, 'es'))
    spa_word.save()

    # french word processing
    result2 = translator.translate(new_word, lang_tgt='fr')
    if isinstance(result2, list):
        result2 = result2[0]

    result2 = re.sub("[^a-zA-Z']+", '', result2)
    fr_word = FrenchWord(word=result2,
                         definition=translator.translate(definition, 'fr'),
                         word_class=translator.translate(wordClass, 'fr'))
    fr_word.save()

    # russian word processing
    result3 = translator.translate(new_word, lang_tgt='ru')
    if isinstance(result3, list):
        result3 = result3[0]
        result3 = re.sub("[^\\w-]+", '', result3)

    rus_word = RussianWord(word=result3,
                           definition=translator.translate(definition, 'ru'),
                           word_class=translator.translate(wordClass, 'ru'))
    rus_word.save()

    add_master_dict(
        EnglishWord.objects.filter(word=result).first(),
        SpanishWord.objects.filter(word=result1).first(),
        FrenchWord.objects.filter(word=result2).first(),
        RussianWord.objects.filter(word=result3).first())
    # print(native_lang)
    # print(result3)
    if native_lang == "English":
        print("saved word (EN)")
        return result
    if native_lang == "Spanish":
        print("saved word (SP)")
        return result1
    if native_lang == "French":
        print("saved word (FR)")
        return result2
    if native_lang == "Russian":
        print("saved word (RU)")
        return result3
Ejemplo n.º 21
0
tokens = nltk.word_tokenize(s)
print(tokens)
'''

f = open("text.txt", "r")
#s = nltk.word_tokenize(f.read())

tokenizer = RegexpTokenizer('\w+')
s = tokenizer.tokenize(f.read())

freq = nltk.FreqDist(x.lower() for x in s)
#freq = dict(freq)

#print(freq.most_common(100))
#print(freq)

print('--------------------\n\n')
#print(stopwords.words('english'))

#dictionary

from PyDictionary import PyDictionary

dictionary = PyDictionary("hotel", "cricket")
#There can be any number of words in the Instance

#print(dictionary.printMeanings()) #This print the meanings of all the words
print(dictionary.getMeanings())  #This will return meanings as dictionaries
#print(dictionary.getSynonyms())
tokens = nltk.word_tokenize(s)
print(tokens)
'''

f = open("text.txt","r")
#s = nltk.word_tokenize(f.read())

tokenizer = RegexpTokenizer('\w+')
s = tokenizer.tokenize(f.read())

freq = nltk.FreqDist(x.lower() for x in s)
#freq = dict(freq)

#print(freq.most_common(100))
#print(freq)

print('--------------------\n\n')
#print(stopwords.words('english'))

#dictionary

from PyDictionary import PyDictionary

dictionary=PyDictionary("hotel","cricket")
#There can be any number of words in the Instance

#print(dictionary.printMeanings()) #This print the meanings of all the words
print(dictionary.getMeanings())   #This will return meanings as dictionaries
#print(dictionary.getSynonyms())

Ejemplo n.º 23
0
import warnings
warnings.filterwarnings("ignore",
                        category=UserWarning,
                        module='beautifulsoup4')

from PyDictionary import PyDictionary

dictionary = PyDictionary("hotel", "ambush", "nonchalant", "perceptive")

'There can be any number of words in the Instance'

print(dictionary.printMeanings())
print(dictionary.getMeanings())
print(dictionary.getSynonyms())
Ejemplo n.º 24
0
                start_search_index = 0
                while search_more:
                    try:
                        found_at_index = words_list.chosen_word.index(guess, start_search_index)
                        blank_word[found_at_index] = guess
                        start_search_index = found_at_index + 1
                    except:
                        search_more = False
                        
            print("".join(blank_word))

            if attempts == 0:
                print("Sorry, the game is over. The word was " + words_list.chosen_word.upper())
                try:
                    my_dict = PyDictionary(words_list.chosen_word)
                    print(my_dict.getMeanings())
                except:
                    print("Not found")
                print("\nWould you like to play again?")
                response = input("> ").lower()
                if response not in ("yes", "y"):
                    play_again = False
                break

            if "_" not in blank_word:
                print("Congratulation! " + words_list.chosen_word.upper() + " was the word.")
                try: 
                    my_dict = PyDictionary(words_list.chosen_word)
                    print(my_dict.getMeanings())
                except:
                    print("Not found")
Ejemplo n.º 25
0
from PyDictionary import PyDictionary
word = input('Word?<user inputs a word>:\t')
try:
    myDict = PyDictionary(word)
    print(myDict.getMeanings())
except:
    print(word, 'Not found')
def getMeanings(text):
    ''' Get the meanings from PyDictionary Library '''

    dictionary = PyDictionary(text)
    meanings = dictionary.getMeanings()
    return meanings