コード例 #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())
コード例 #2
0
ファイル: Dictionary.py プロジェクト: JaydeepDPatil/JARVIS
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())
コード例 #3
0
def similarity_result(data, keyword):
    '''
	@data : dataframe with  pruned data
	@keyword : list of token in keyword
	'''
    keyword = [w.lstrip() for w in keyword]
    keywordsWithSynonyms = []
    dictionary = PyDictionary(keyword)
    for i, w in enumerate(keyword):
        synonyms = dictionary.getSynonyms()[i]
        keywordsWithSynonyms.append(w)
        if not synonyms is None:
            keywordsWithSynonyms += synonyms[w]
    keywordsWithSynonyms = [ps.stem(w) for w in keywordsWithSynonyms]
    reviews = getreview()
    rank = []
    for i, text in enumerate(data['description']):
        #perform jaccard
        scores = 0
        # remove punctuation
        tokens = text.strip(string.punctuation)
        tokens = tokens.lower().split()
        # stem the token
        tokens = [ps.stem(w) for w in tokens]

        intersection = len(
            list(set(tokens).intersection(set(keywordsWithSynonyms))))
        union = (len(tokens) + len(keywordsWithSynonyms)) - intersection
        if (union == 0):
            print("union is 0")
        scores += float(intersection) / union

        list_id = data.iloc[i]['id']

        #jaccard on amenities
        amenities = data.iloc[i]['amenities']
        amenities = [ps.stem(w.lower()) for w in amenities]
        intersection = len(
            list(set(amenities).intersection(set(keywordsWithSynonyms))))
        union = (len(amenities) + len(keywordsWithSynonyms)) - intersection
        scores += float(intersection) / union

        # compute the similairty score for review also
        for rev in reviews[reviews.listing_id == list_id]['comments']:
            tokens = rev.strip(string.punctuation)
            tokens = tokens.lower().split()
            tokens = [ps.stem(w) for w in tokens]
            intersection = len(
                list(set(tokens).intersection(set(keywordsWithSynonyms))))
            union = (len(tokens) + len(keywordsWithSynonyms)) - intersection
            scores += float(intersection) / union

        rank.append((scores, i))
    rank = sorted(rank, key=lambda tup: tup[0], reverse=True)
    # get the sorted index
    ranked_i = [doc[1] for doc in rank]
    scores = [doc[0] for doc in rank]
    return data.iloc[ranked_i], scores
コード例 #4
0
    def syno(self):

        dictionary = PyDictionary(self.root.ids.antosyno.text)
        word = str(self.root.ids.antosyno.text)
        synonym = list(dictionary.getSynonyms())
        d = synonym[0][word][:4]
        e = ",".join(d)
        self.root.ids.antosynom.text = e
        self.speak(e)
コード例 #5
0
def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')
    try:
        req_body = req.get_json()
    except ValueError:
        pass
    else:
        words = req_body.get('words')

    if len(words) > 0 and type(words) is list:
        result = {}
        for word in words:
            synsets = wn.synsets(word, pos='n')
            similar_words = []
            if len(synsets) > 0:
                synset = synsets[0]
                # Get the hypernym for this synset (again, take the first)
                hypernyms = synset.hypernyms()
                if len(hypernyms) > 0:
                    hypernym = hypernyms[0]
                    # Get some hyponyms from this hypernym
                    hyponyms = hypernym.hyponyms()
                    # Take the name of the first lemma for the first 8 hyponyms
                    for hyponym in hyponyms:
                        similar_word = hyponym.lemmas()[0].name().replace(
                            '_', ' ').replace('-', ' ')
                        if similar_word != word:
                            similar_words.append(similar_word)
            dictionary = PyDictionary(word)
            synonyms = dictionary.getSynonyms()
            if len(synonyms) > 0 and synonyms[
                    0] is not None and word in synonyms[0].keys():
                answer = synonyms[0][word]
                print(answer)
                similar_words = similar_words + answer

            opposite_words = []
            antonyms = dictionary.getAntonyms()
            if len(antonyms) > 0 and antonyms[
                    0] is not None and word in antonyms[0].keys():
                opposite_words = antonyms[0][word]
            result[word] = {"synms": similar_words, "antms": opposite_words}
        return func.HttpResponse(json.dumps(result),
                                 mimetype="application/json",
                                 status_code=200)
    else:
        return func.HttpResponse(
            "This HTTP triggered function executed successfully. Pass a word in the query string or in the request body for a personalized response.",
            status_code=201)
コード例 #6
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
コード例 #7
0
class Dictionary:
    def __init__(self, query, get_synonyms=False):
        self.dictionary = PyDictionary()
        self.meaning = self.dictionary.meaning(query)
        self.synonyms = self.get_synonyms(query)
        if get_synonyms:
            self.synonyms = self.get_synonyms(query=query)

    def get_synonyms(self, query):
        return self.dictionary.getSynonyms(query)

    def get_meaning(self):
        return self.meaning

    def get_dict(self):
        dictin_empty = {'Noun': None, 'Verb': None, 'Adj': None}
        dicti = self.meaning
        if 'Noun' in dicti.keys():
            dictin_empty['Noun'] = dicti['Noun']
        if 'Verb' in dicti.keys():
            dictin_empty['Verb'] = dicti['Verb']
        if 'Adjective' in dicti.keys():
            dictin_empty['Adj'] = dicti['Adjective']
        return dictin_empty
コード例 #8
0
import pickle
from PyDictionary import PyDictionary

with open('../vocab', 'rb') as f:
    load_dict = pickle.load(f)
    vocab = list(load_dict.keys())

    dictionary = PyDictionary(vocab)
    sym = dictionary.getSynonyms()
    ant = dictionary.getAntonyms()

    symMap = {}
    antMap = {}

    for d in sym:
        if d is not None:
            symMap.update(d)

    for d in ant:
        if d is not None:
            antMap.update(d)

    with open('vocab_sym', 'wb') as sym_f:
        pickle.dump(sym, sym_f, 2)

    with open('vocab_ant', 'wb') as ant_f:
        pickle.dump(ant, ant_f, 2)
コード例 #9
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())
コード例 #10
0
    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')
コード例 #11
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")
    
コード例 #12
0
ファイル: david.py プロジェクト: shlomo-maghen/webdev-chatbot
import webcolors
import json
import urllib

BOT_NAME = "ADINA"
###########################################################
#   File name: main.py
#   Author: David Moyal / Shlomo Maghen / Samuel Jefroykin
#   Last updated : 01/18/2017
###########################################################
dictionary = PyDictionary('headline', 'title', 'image', 'picture', 'paragraph',
                          'text', 'url-link', 'link', 'access', 'redirection',
                          'button', 'box', 'video', 'map', 'footer', 'big',
                          'small', 'medium')

synonyms = dictionary.getSynonyms()
title_syn = synonyms[1]['title'] + synonyms[0]['headline'] + [
    'headline', 'title', 'name', 'haedline', 'tilte', 'tile'
]
image_syn = synonyms[2]['image'] + synonyms[3]['picture'] + [
    'image', 'picture', 'img', 'pic', 'imge'
]
paragraph_syn = synonyms[4]['paragraph'] + synonyms[5]['text'] + [
    'paragraph', 'text', 'txt', 'par', 'texte'
]
link_syn = synonyms[6]['url-link'] + synonyms[7]['link'] + synonyms[8][
    'access'] + synonyms[9]['redirection'] + [
        'link', 'url link', 'access', 'redirection', 'lnk'
    ]
button_syn = synonyms[10]['button'] + ['button', 'buton', 'buttn']
navigation_bar_syn = ['navbar', 'navigation bar', 'nav bar']