Ejemplo n.º 1
0
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)
Ejemplo n.º 2
0
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
Ejemplo n.º 3
0
def game():
    words = create_word_list()
    lookup = PyDictionary()
    global attempts, wins
    idx = 0
    answer = random.choice(words)
    while idx < 3:
        clue = lookup.synonym(answer)[idx]
        now = time.time()
        future = now + 10
        print('\nClue: ' + clue)
        guess = input('Guess: ').lower()
        if guess == answer or guess + 's' == answer or guess == answer[:-3]:
            print("\nCorrect!")
            wins += 1
            break
        elif now > future:
            print("You ran out of time! The answer was %s." % answer)
            break
        else:
            print("\nWrong.")
            idx += 1
            if idx == 3:
                print("\nThe answer was %s." % answer)

    attempts += 1
    print("Game over. Your score was %d / %d." % (wins, attempts))
    print('-' * 10)
    words.remove(answer)
    restart()
Ejemplo n.º 4
0
    async def synonym(self, word):
        """Checks the dictionary for the synonyms for a given word."""

        word = word.lower()
        result = dictionary.synonym(word)
        try:
            text = self.nym_text_format("synonyms", result, word)
            return await self.bot.say(text)
        except TypeError:
            return await self.bot.say("No results found. Are you " +
                                      "searching for a valid word?")
Ejemplo n.º 5
0
class Synsets(object):
    def __init__(self, synsets={}): # synsets are hashmap of (string:Word objects) pair
        self.dictionary = PyDictionary()
        self.synsets = synsets

    def find(self, word):
        try:
            return map(str, self.dictionary.synonym(word))
        except:
            if word not in synsets:
                return []
            return synsets[word].synonyms

    def add(self, synsets):
        self.synsets.update(synsets)
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")
Ejemplo n.º 7
0
     input = response
     (a,b,c,d) =[t(s) for t,s in zip((str,int,str,int),re.search('^(\w+) (\d+) (\w+) (\d+)$',input).groups())]
     result = int(b*d)
     print(result)
 elif('divide') in response :
     input = response
     (a,b,c,d) =[t(s) for t,s in zip((str,int,str,int),re.search('^(\w+) (\d+) (\w+) (\d+)$',input).groups())]
     result = float(b/d)
     print(result)
 elif('define') in response:
     query = response
     stopwords = ['define']
     querywords = query.split()
     resultwords  = [word for word in querywords if word.lower() not in stopwords]
     result = ''.join(resultwords)
     rand = (dictionary.synonym(result))
     print(rand)
 elif('tell me a joke')in response:
     rand=(pyjokes.get_joke())
     print(rand)
 elif response == ("do you have a brother"):
     print("yes")
 elif response == "thanks" or response == "thank you":
     print("mhm")
 elif response == ("what is your brothers name"):
     print("jarvis")
 elif response == ("who created you"):
     print("zpit367")
 elif response == ("what language were you coded in"):
     print("python")
 elif response == "what is your name":
Ejemplo n.º 8
0
    words2d = [{i[0] : i[-1]} for i in reader]

pd = PyDictionary()
enhanced_word_sets = []  # Дополненные списки слов(включая синонимы) - обычно в 5 раз длиннее
MATRIX = [[0]*2346]*2346

for words in words2d[1:]:
    res = set()
    id = [int(i) for i in words.keys()][0]
    if words:
        for value in words.values():  # Обходим каждое слово, превращаем его в синонимы, добавляем в сет
            en_words = [word for word in TextBlob(value).translate("ru").split() if word not in
"a about an are as at be by com for from how in is it of on or that the this to was what when where who will with the"]
            rus_synonyms = ""
            for word in en_words:
                synonyms = pd.synonym(word.split()[-1])
                if synonyms:
                    rus_synonyms += " ".join(synonyms) + " "
        for word in TextBlob(rus_synonyms).translate("en", "ru").split():
            res.add(word)

    print("Завершено создание расширенного списка слов для", id, "из 2346")
    enhanced_word_sets.append((id, res))

i = 1
for set_ in enhanced_word_sets:
    for _set in enhanced_word_sets:
        _id_ = set_[0], _set[0]
        if not _id_[0] == _id_[1]:
            index = len(set_[1] & _set[1]) / len(set_[1] | _set[1])  # Индекс схожести
            if 0.25 <= index < 1:
Ejemplo n.º 9
0
def most_similar(word):
	queries = [w for w in word.vocab if w.is_lower == word.is_lower and w.prob >= -15]
	by_similarity = sorted(queries, key=lambda w: word.similarity(w), reverse=True)
	return by_similarity[:10]


mostSim = [w.lower_ for w in most_similar(nlp.vocab[u'dog'])]

# Gensim

from gensim.models import KeyedVectors

model = KeyedVectors.load_word2vec_format('GoogleGoogleNews-vectors-negative300.bin', binary=True)

#vector = model['easy']
model.similarity('aWord','aWord2')
model.most_similar('dog')

# NLTK

from nltk.corpus import wordnet as wn
print wn.synset("eat.v.01").lemma_names # prints synonyms of eat

# PyDictionary

from PyDictionary import PyDictionary

dictionary=PyDictionary()
dictionary.synonym("Life")
Ejemplo n.º 10
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
Ejemplo n.º 11
0
# im.show()

while True:
    # part of the screen
    im = ImageGrab.grab(bbox=(870, 200, 1670, 1000))  # x1, y1 | x2 y2
    im.save("img.jpg")
    img = cv2.imread("img.jpg")

    # Getting text from image
    text = pytesseract.image_to_string(img)
    print(text)

    # Breaking down the spaced out words into lists and strings
    possible_options = list(filter(None, text.split('\n')[:-1]))[1::]
    word_to_search = list(filter(None, text.split('\n')[:-1]))[0][:-7]
    possible_meanings = dictionary.synonym(word_to_search)

    print("----")
    print(word_to_search)
    print(possible_options)
    print(possible_meanings)
    print("----")

    # Checking against the dictionary

    wordFound = False
    if possible_meanings == None:
        possible_meanings = ['t']

    for i in range(len(possible_options)):
        for j in range(len(possible_meanings)):
Ejemplo n.º 12
0
creds = ServiceAccountCredentials.from_json_keyfile_name("client_secret.json", scope)
client = gspread.authorize(creds)
sheet = client.open("Students (Responses)").sheet1

person = sheet.row_values(sheet.row_count)
# for every response to the survey
words = person[11].split(" ")

# Whole thing checks if any words are adjectives and gets their synonyms
for w in words:
    if wn.synsets(w):

        tmp = wn.synsets(w)[0].pos()
        if tmp == "a":
            print(w, ":", tmp)
            wSynonym = dictionary.synonym(w)
            synonyms += wSynonym

print(synonyms)

# Start of employers lists
# These are fake companies (some are based on real companies), you can tell from the names
# Some of the subjects for some of the employers aren't super realistic, but others are
# I just put in what came to mind for variety, Also locations are also fictional
# A proper version would have actual employers with actual locations and what not
# The values in the list are based on the spreadsheet questions
# Values are randomised externally (not in the website for consistency) using random.org, so they're not real values

employer1 = [2020, "computerland", "Belait", True, ["English", "History", "Business", "Computer Science"], 1, 5, 6, 4, 6, True, ['honest', 'confident', 'adventurous', 'productive', 'original', 'courteous']]
employer2 = [2020, "novideo", "Belait", False, ["Maths", "Computer Science", "Business", "Economics", "Physics"], 2, 5, 10, 8, 10, False, ['positive', 'creative thinking', 'reliable', 'confident', 'agreeable', 'considerate']]
employer3 = [2020, "ayyyymd", "Brunei-Muara", False, ["Maths", "Computer Science", "Business", "Economics", "Physics"], 4, 10, 3, 3, 10, True, ['positive', 'honest', 'reliable', 'confident', 'agreeable', 'adventurous']]
Ejemplo n.º 13
0
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)
Ejemplo n.º 14
0
def analyze(request):

    puncts = string.punctuation
    word_to_find = request.POST.get("word_input")
    djText = request.POST.get('text', 'default')
    remPunc = request.POST.get('option', 'removepunc')
    cap = request.POST.get('option', 'capitalize')
    small = request.POST.get('option', 'toSmall')
    upper = request.POST.get('option', 'toUpper')
    word_find_flag = request.POST.get('option', 'word_find')
    New_Line = request.POST.get('option', 'New_line')
    Emails = request.POST.get('option', 'Email_Address')
    Links = request.POST.get('option', 'Links')
    Passgen = request.POST.get('option', 'Password_Generator')
    search_word = request.POST.get('option', 'Search_word')
    gallery = request.POST.get('option', 'q')
    Suggest_word = request.POST.get('option', 'suggest_word')
    Sen_Analysis = request.POST.get('option', 'Sentiment')
    Grammar = request.POST.get('option', 'grammar')
    Channel = request.POST.get('option', 'suggest_youtube')
    books = request.POST.get('option', 'suggest_books')
    articles = request.POST.get('option', 'suggest_articles')
    lemmitizer = request.POST.get('option', 'grammar')
    start_pdf = request.POST.get('option', 'generate_pdf')
    replace_text = request.POST.get('option', 'replace')
    Word_cloud = request.POST.get('option', 'wordcloud')
    Date = request.POST.get('option', 'date')
    Word_frequency = request.POST.get('option', 'word_frequency')

    analyzed_text = ""
    word_status = ""

    countword = len(djText.split())

    if word_find_flag == "word_find":
        if word_to_find != "":
            if djText.find(word_to_find) != -1:
                word_status = "found"
                word = djText.replace(
                    word_to_find,
                    f"""<b style="color:{"red"};">""" + word_to_find + "</b>")
                djText = word

                try:
                    synonym_01 = get_synonyms(word_to_find)
                    synonyms2 = random.sample(synonym_01, 4)

                    final = ""
                    for f in synonyms2:
                        final += f + " , "

                    example = get_example(word_to_find)

                    synonyms = final + example

                except:
                    synonyms = "Not Available"

            else:
                word_status = "not found"
                synonyms = "Text Not Found"

            analyzed_text = djText
            word_find = "Find Word = " + word_to_find
            synonym = format_html('<b style="color:{};">{}</b>', 'green',
                                  synonyms)

            result = {
                "analyzed_text": analyzed_text,
                "highlight":
                "Chosen word is highlighted in red colour and synonyms/examples in green colour",
                "purpose": word_find,
                "status": word_status,
                "synonym": synonym,
                "wordcount": countword,
                "analyze_text": True,
                "findWord": True
            }

    elif New_Line == "New_line":
        for char in djText:
            if char == '.':
                char = '\n'
            analyzed_text = analyzed_text + char
        result = {
            "analyzed_text": analyzed_text,
            "purpose": "Changes '.' to New Line",
            "analyze_text": True,
            "wordcount": countword
        }
    elif Emails == "Email_Address":
        regex = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$'
        lst = re.findall('\S+@+\S+', djText)
        tmp = ""
        for x in lst:
            if (re.search(regex, x)):
                tmp += x
                tmp += '\n'
        result = {
            "analyzed_text": tmp,
            "purpose": "Find All Emails",
            "analyze_text": True,
            "wordcount": countword
        }

    elif Passgen == "Password_Generator":
        stop_words = set(stopwords.words('english'))
        chars = "!£$%&*#@"
        ucase_letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        text = re.sub(r'[^\w\s]', '', djText)
        token = word_tokenize(text)

        filtered_sentence = []

        for w in token:
            if w not in stop_words:
                filtered_sentence.append(w)

        if len(filtered_sentence) > 0:
            random_word = random.choice(filtered_sentence)
        else:
            random_word = token[0]

        random_word = random_word.title()

        merge = ""
        for word in random_word.split():
            merge+=random.choice(chars)+word[:-1]+ word[-1].upper()\
            +random.choice(string.ascii_letters)+"@"+random.choice(ucase_letters)\
            +random.choice(string.digits)+" "
        final_text = merge[:-1]
        result = {
            "analyzed_text": final_text,
            "purpose": "Generate password from text",
            "generate_text": True,
            "wordcount": countword
        }

    elif search_word == "Search_word":
        url = 'https://www.dictionary.com/browse/'
        headers = requests.utils.default_headers()
        headers.update({
            'User-Agent':
            'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36'
        })
        req = requests.get(url + djText, headers)
        soup = BeautifulSoup(req.content, 'html.parser')
        mydivs = soup.findAll("div", {"value": "1"})[0]
        for tags in mydivs:
            meaning = tags.text
        wrap = textwrap.TextWrapper(width=100)
        word_meaning = wrap.fill(text=meaning)
        result = {
            "analyzed_text": word_meaning,
            "purpose": "Searched Word",
            "generate_text": True,
            "wordcount": countword
        }

    elif Suggest_word == "suggest_word":
        find = requests.get(
            f"https://www.dictionaryapi.com/api/v3/references/thesaurus/json/{djText}?key={api_key}"
        )
        response = find.json()

        if len(response) == 0:
            print("Word Not Recognized!")
        else:
            k = []
            if str(response[0]).count(" ") == 0:
                for j in range(len(response)):
                    k.append(response[j])
                predict = " , ".join(k)
                djText = predict

            else:
                dictionary = PyDictionary()
                testdict = dictionary.synonym(djText)
                suggest = " , ".join(testdict)
                djText = suggest
            wrap = textwrap.TextWrapper(width=100)
            suggest = wrap.fill(text=djText)

        result = {
            "analyzed_text": suggest,
            "purpose": "Suggested Word",
            "generate_text": True,
            "wordcount": countword
        }

    elif Sen_Analysis == "Sentiment":

        djText = ' '.join(
            re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ",
                   djText).split())

        analysis = TextBlob(djText)
        # set sentiment
        if analysis.sentiment.polarity > 0:
            final = str(djText) + " (Positive Text)"
        elif analysis.sentiment.polarity == 0:
            final = str(djText) + " (Neutral Text)"
        else:
            final = str(djText) + " (Negative Text)"

        result = {
            "analyzed_text": final,
            "purpose": "Sentiment Analysis",
            "analyze_text": True,
            "wordcount": countword
        }

    elif Grammar == "grammar":
        parser = GingerIt()
        result = parser.parse(djText)
        final = result["result"]

        if final == '':
            final = "Please write some text to check grammar"

        result = {
            "analyzed_text": final,
            "grammar": djText,
            "purpose": "Spelling & Grammar Check",
            "analyze_text": True,
            "wordcount": countword
        }

    elif lemmitizer == "lemmitize":
        wordnet_lemmatizer = WordNetLemmatizer()
        tokenization = nltk.word_tokenize(djText)
        count = True
        for w in tokenization:
            k = wordnet_lemmatizer.lemmatize(w, pos="v")
            if w != k:
                result = "{} -> {}".format(
                    w, wordnet_lemmatizer.lemmatize(w, pos="v"))
                count = False
        if count == True:
            final = "No need for lemmatization"
        if count == False:
            final = "(Original word) - > (Lemmatized word)"

        result = {
            "analyzed_text": result,
            "highlight": final,
            "purpose": "Lemmatization of text",
            "analyze_text": True,
            "wordcount": countword
        }

    elif Channel == "suggest_youtube":
        request.session['user-input'] = djText
        result = {
            "analyzed_text": djText,
            "purpose": "Suggest youtube channels",
            "status": "Press Button To View Channel links",
            "find_channel": True,
            "generate_text": True,
            "wordcount": countword
        }

    elif books == "suggest_books":
        request.session['user-input'] = djText
        result = {
            "analyzed_text": djText,
            "purpose": "Search Books",
            "status": "Press Button To View Books",
            "find_books": True,
            "generate_text": True,
            "wordcount": countword
        }

    elif articles == "suggest_articles":
        request.session['user-input'] = djText
        result = {
            "analyzed_text": djText,
            "purpose": "Search Articles",
            "status": "Press Button To View Articles",
            "find_articles": True,
            "generate_text": True,
            "wordcount": countword
        }

    elif start_pdf == "generate_pdf":
        request.session['user-input'] = djText
        result = {
            "analyzed_text": "Check Your Pdf",
            "purpose": "Generate Pdf",
            "status": "Press Button To View Pdf",
            "make_pdf": True,
            "generate_text": True,
            "wordcount": countword
        }

    elif replace_text == "replace":
        final_text = re.sub(word_to_find, replace_input, djText)
        result = {
            "analyzed_text": final_text,
            "purpose": "Replacemet of text in sentence",
            "analyze_text": True,
            "wordcount": countword
        }

    elif Word_cloud == "wordcloud":
        cloud = WordCloud(background_color="white",
                          max_words=200,
                          stopwords=set(STOPWORDS))
        wc = cloud.generate(djText)
        buf = io.BytesIO()
        wc.to_image().save(buf, format="png")
        data = base64.b64encode(buf.getbuffer()).decode("utf8")
        final = "data:image/png;base64,{}".format(data)

        result = {
            "analyzed_text": " ",
            "purpose": "Wordcloud",
            "my_wordcloud": final,
            "generate_text": True,
            "wordcount": countword
        }

    elif Date == "date":
        final = extract_dates(djText)
        final_text = final[0].date()

        result = {
            "analyzed_text": final_text,
            "purpose": "Extract Dates from text",
            "analyze_text": True,
            "wordcount": countword
        }

    elif Word_frequency == "word_frequency":
        input_text = djText.replace("\n", " ")
        djText = input_text.lower()

        words_dict = get_words_dict(djText)
        # create graph
        if len(words_dict) > 10:
            k = 10
        else:
            k = len(words_dict)

        y_pos = range(0, k)
        bars = []
        height = []
        count = 0

        # print and save values to graph
        format_spaces("word", "occurrences")
        for word_str, word_amount in words_dict.items():
            format_spaces(word_str, word_amount)
            count += 1
            if count <= 10:
                bars.append(word_str)
                height.append(int(word_amount))
            else:
                pass

        # # Create bars
        plt.bar(y_pos, height)

        # Create names on the x-axis
        plt.xticks(y_pos, bars, size=9)

        plt.xticks(rotation='horizontal')
        plt.ylabel('Word Frequency', fontsize=12, labelpad=10)
        plt.xlabel('Words', fontsize=12, labelpad=10)

        fig = plt.gcf()

        buf = BytesIO()
        fig.savefig(buf, format='png')
        buf.seek(0)
        data = base64.b64encode(buf.read())
        uri = urllib.parse.quote(data)
        final = "data:image/png;base64,{}".format(uri)

        result = {
            "analyzed_text": " ",
            "purpose": "Word Frequency for every word in text",
            "bar_graph": final,
            "analyze_text": True,
            "wordcount": countword
        }

    elif gallery == "q":
        request.session['user-input'] = djText
        result = {
            "analyzed_text": djText,
            "purpose": "Images",
            "status": "Press Button To View Images",
            "find_image": True,
            "generate_text": True,
            "wordcount": countword
        }

    elif remPunc == 'removepunc':
        for char in djText:
            if char not in puncts:
                analyzed_text = analyzed_text + char
        result = {
            "analyzed_text": analyzed_text,
            "purpose": "Remove Punctuations",
            "analyze_text": True,
            "wordcount": countword
        }
    elif cap == "capitalize":
        analyzed_text = djText.capitalize()

        result = {
            "analyzed_text": analyzed_text,
            "purpose": "Capitalize",
            "analyze_text": True,
            "wordcount": countword
        }

    elif small == "toSmall":
        analyzed_text = djText.lower()

        result = {
            "analyzed_text": analyzed_text,
            "purpose": "To Smallercase",
            "analyze_text": True,
            "wordcount": countword
        }

    elif upper == "toUpper":
        analyzed_text = djText.upper()

        result = {
            "analyzed_text": analyzed_text,
            "purpose": "To Uppercase",
            "analyze_text": True,
            "wordcount": countword
        }
    elif Links == "Links":
        pattern = '(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[-A-Z0-9+&@#\/%=~_|$?!:,.])*(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[A-Z0-9+&@#\/%=~_|$])'
        links = re.findall(pattern, djText, re.IGNORECASE)
        analyzed_text = ""

        i = 0
        for x in links:
            i = i + 1
            analyzed_text += f'<a href="{x}" target="_blank">Link {i}</a>'
            analyzed_text += '\n '

        result = {
            "analyzed_text": analyzed_text,
            "purpose": "Find All Links",
            "analyze_text": True,
            "wordcount": countword
        }

    else:
        return HttpResponse(
            '''<script type="text/javascript">alert("Please select atleast one option.");</script>'''
        )

    return render(request, 'analyze.html', result)
Ejemplo n.º 15
0
def detectDisplayNamedEntities(sentence):
    ##############if we use buit in pos result owuld be better ######
    # I have trained my own POS tagger as well butits accuracy is around 80 to 90 % I can use that as well
    tokens = nltk.word_tokenize(sentence)
    resultList2 = list(nltk.pos_tag(tokens))
    print(resultList2)
    #grammar = "NP: {<DT>?<JJ>*<NN>}" # for desired resutlt we can update the grammer
    grammar2 = r"""
      NP: {<DT|PP\$>?<JJ>*<NN>}   # chunk determiner/possessive, adjectives and noun
          {<NNP>+}                # chunk sequences of proper nouns
          {<NNS>+}                # chunk sequences of Noun plural
          {<NNPS>+}                # chunk sequences of Proper noun, plural
          {<LS>+}                # chunk sequences of List item marker
    """

    cp = nltk.RegexpParser(grammar2)
    nounPhraseTree = cp.parse(resultList2)
    print(nounPhraseTree)

    print(
        "**** -below is the output from code to extract realtion between entities by library--****"
    )
    relationResult = relextract.tree2semi_rel(nounPhraseTree)
    for s, tree in relationResult:
        print(str(s) + " has something to do with:  " + str(tree))

    # uncomment line below ehn you want to see the tree structure of tags as well
    #nounPhraseTree.draw()

    nounList = []
    for node in nounPhraseTree:
        if isinstance(node, nltk.tree.Tree):
            if node.label() == 'NP':
                NP = node.leaves()
                print(NP)
                for x in NP:
                    if x[1] == 'NN' or x[1] == 'NNP' or x[1] == 'NNPS' or x[
                            1] == 'NNS':
                        nounList.append(x[0])

    print(
        "*****-----------------------------------------------------------*****"
    )
    print("list of all nouns detected in the text is result as below:")
    print(nounList)
    dictionary = {}
    dictionary['coutries'] = []

    #    with open('countries.txt') as openfileobject:
    #        for line in openfileobject:
    #            dictionary['coutries'].append(line.rstrip())
    #        openfileobject.closed

    fileHandler = open('countries.txt')
    allCountries = fileHandler.read()
    fileHandler.close()
    dictionary['coutries'] = allCountries.split("\n")

    fileHandler = open('months.txt')
    allCountries = fileHandler.read()
    fileHandler.close()
    dictionary['months'] = allCountries.split("\n")

    fileHandler = open('days.txt')
    allCountries = fileHandler.read()
    fileHandler.close()
    dictionary['days'] = allCountries.split("\n")
    ### same way we can use different dictionalries to tag detail with our detected nouns
    #print(dictionary['coutries'][1])
    finalNamedEntityWithEntityTags = []

    for n in nounList:  # here by n I mean one noun from the list of nouns
        if n in dictionary['coutries']:
            finalNamedEntityWithEntityTags.append((n, 'name of Country'))
        if n in dictionary['months']:
            finalNamedEntityWithEntityTags.append((n, 'name of Month'))
        if n in dictionary['days']:
            finalNamedEntityWithEntityTags.append((n, 'Day of the week'))

    for resultLine in finalNamedEntityWithEntityTags:
        print(resultLine)

    finalNERWithDetail = []
    dictionary = PyDictionary()
    for n in nounList:
        # this will help user to understand detected NER
        try:  #try block if dictionary has no synonyn then its a name
            finalNERWithDetail.append((n, dictionary.synonym(n)))
        except:
            finalNERWithDetail.append(
                (n, "it is a name of something or a person"))

    print(
        "=> Detected NER with synonym detail that help to understand these NER: "
    )
    for resultLine in finalNERWithDetail:
        print(resultLine)
Ejemplo n.º 16
0
# STEP 5: BODYPARTS ##########################################################################

# We want to first get every synonym for every body part, then search in text.
terms = json.load(open("data/simpleFMA.json","r"))
dictionary=PyDictionary()

# looked at these manually, these are the ones worth adding
get_synsfor = ["stomach","cartilage","breast","knee","waist","muscle","tendon","calf",
               "v****a","penis","back","butt","forearm","thigh"]

bodyparts = dict()
for term,fma in terms.iteritems():
    syns = ""
    word = term.replace("_"," ")
    if term == "index-finger":
        syns = dictionary.synonym("index-finger")
    elif term in get_synsfor:
        syns = dictionary.synonym(term)
    if syns != "":
        regexp = "|".join([word] + syns)
    else:
        regexp = "|".join([word])
    bodyparts[term] = regexp
    
save_json(bodyparts,"data/bodyparts.json")

# Now let's parse each death for bodyparts
injuries = pandas.DataFrame(columns=bodyparts.keys())

for row in fatalities.iterrows():
    index = row[0]
def getSyn(word):
    dic = PyDictionary() 
    syn = dic.synonym(word)
    return syn
Ejemplo n.º 18
0
        print bot_response
    elif message.strip().split()[0] == "tweet":
        flag = None
        tw = Tweets_cassandra.TweetAPI()
        try:
            flag = 0
            tw.postTweet(" ".join(message.strip().split()[1:]))
        except:
            flag = 1
        if (flag == 0 ):
            print "Tweet successful"
        else:
            print "Tweet Failed"

    elif " ".join(message.strip().lower().split()[:2]) == "synonym of":
        bot_response =  dictionary.synonym(" ".join(message.strip().lower().split()[2:]))
        if(len(bot_response) >= 1 ):
            bot_response = ", ".join(bot_response)
        else:
            bot_response = "Sorry i couldn't find the synonym for "," ".join(bot_response)
        print bot_response

    elif " ".join(message.strip().lower().split()[:2]) == "antonym of":        
        bot_response =  (dictionary.antonym(" ".join(message.strip().lower().split()[2:])))
        if(len(bot_response) >= 1 ):
            bot_response = ", ".join(bot_response)
        else:
            bot_response = "Sorry i couldn't find the antonym for "," ".join(bot_response)
        print bot_response

Ejemplo n.º 19
0
import nltk
from nltk import pos_tag
from nltk.corpus import wordnet as wn
from PyDictionary import PyDictionary
#from iertools import chain
dictionary=PyDictionary()
text = nltk.word_tokenize("instantiate variable")
tags= nltk.pos_tag(text)
words=[]
for word in tags:
	if word[1] == 'NN' and len(word[0])>1:
		words.append(word[0])
		print dictionary.synonym(word[0])
		print word

'''
synonyms = wordnet.synsets(text)
lemmas = set(chain.from_iterable([word.lemma_names() for word in synonyms]))
wn.synsets('make', pos='v')'''
# Access most recent Tweet from account
tweets = api.user_timeline('RelatedWordsBot')
mostRecent = tweets[0]

contents = str(mostRecent.text)
index = 0

for x in range(0, len(contents)):
    if (contents[x] == " "):
        index = x

# Word to generate related word from
searchWords = contents.split(" ")
searchWord = searchWords[len(searchWords) - 2].replace(" ", "")

relatedWords = dictionary.synonym(searchWord)

relatedWord = relatedWords[0]

# Word previously generated by bot
prevWord = contents[0 : index]

# Get the image previously generated by the bot
for media in mostRecent.entities.get("media",[{}]):
    #checks if there is any media-entity
    if media.get("type",None) == "photo":
        # checks if the entity is of the type "photo"
        imgUrl = media["media_url"]
        # save to file etc.

result = sbi.search_by(url=imgUrl)
Ejemplo n.º 21
0
# constants
AT_BOT = "<@" + BOT_ID + ">"
EXAMPLE_COMMAND = "do"

# instantiate Slack & Twilio clients
slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))

cur.execute("SELECT * FROM solutions where questions like '%teacher%'")
for row in cur.fetchall():
    m = row[0]

z = ['professor', 'assistant', 'lecturer', 'tutor']
final1 = []

for i in z:
    list1 = dictionary.synonym(i)
    list1 = [str(i).strip() for i in list1]

    final1.append(list1)


def handle_command(command, channel):

    for i in final1:
        print i
        for j in i:
            if j in command:
                print j
                if command in final1[0] or command in final1[1] or final1[
                        2] or command in final1[3] or command in final1[4]:
                    cur.execute(
Ejemplo n.º 22
0
def synonyms(word):
    synonyms = dictionary.synonym(word)
    return format_synoyms(synonyms)
Ejemplo n.º 23
0
# We want to first get every synonym for every body part, then search in text.
terms = json.load(open("data/simpleFMA.json", "r"))
dictionary = PyDictionary()

# looked at these manually, these are the ones worth adding
get_synsfor = [
    "stomach", "cartilage", "breast", "knee", "waist", "muscle", "tendon",
    "calf", "v****a", "penis", "back", "butt", "forearm", "thigh"
]

bodyparts = dict()
for term, fma in terms.iteritems():
    syns = ""
    word = term.replace("_", " ")
    if term == "index-finger":
        syns = dictionary.synonym("index-finger")
    elif term in get_synsfor:
        syns = dictionary.synonym(term)
    if syns != "":
        regexp = "|".join([word] + syns)
    else:
        regexp = "|".join([word])
    bodyparts[term] = regexp

save_json(bodyparts, "data/bodyparts.json")

# Now let's parse each death for bodyparts
injuries = pandas.DataFrame(columns=bodyparts.keys())

for row in fatalities.iterrows():
    index = row[0]
Ejemplo n.º 24
0
class Synonym:
    """Synonym object is a generator for synonyms. Has:
	- apiUrl: url for Wordnik API
	- apiKey: API access key, obtain from wordnik.com
	- client: API client
	- wordApi: query-able API object
	- dictionary: PyDictionary object (for synonym generation)
	- mod: Modify object for redaction if no substitutes found
	- words_without_synonyms: tracking list of words without synonyms to reduce runtime
	"""
    def __init__(self):
        """Create a Synonym"""
        self.apiUrl = 'http://api.wordnik.com/v4'
        self.apiKey = '789439e487771e1085b261e2bf001749744d0e079512b3549'
        self.client = swagger.ApiClient(self.apiKey, self.apiUrl)
        self.wordApi = WordApi.WordApi(self.client)
        self.dictionary = PyDictionary()
        self.mod = Modify()
        self.words_without_synonyms = dict()

    def find_acceptable_synonym(self, word, banned_chars):
        """Find a synonym for word that does not contain any of banned_chars"""

        #word already known not to have synonym, misspell instead
        if word in self.words_without_synonyms:
            return self.mod.modify_letters(word, banned_chars)

        #find synonym from Wordnik API
        wordnik_syn = self.get_wordnik_syn(word, banned_chars)
        if wordnik_syn is not None:
            return wordnik_syn

        #didn't find wordnik synonym, try PyDict synonym
        pydict_syn = self.get_pydict_syn(word, banned_chars)
        if pydict_syn is not None:
            return pydict_syn

        #couldn't find a synonym - add to list of words w/o synonyms and respell instead
        self.words_without_synonyms[word] = True
        return self.mod.modify_letters(word, banned_chars)

    def get_wordnik_syn(self, word, banned_chars):
        """Get synonym that does not contain any of banned_chars via Wordnik API. If no synonym found, returns None
		"""

        all_syns = self.wordApi.getRelatedWords(word,
                                                relationshipTypes="synonym")

        if all_syns is not None:
            #find first synonym that does not contain any of the banned chars
            for syn in all_syns:
                banned = False
                for char in banned_chars:
                    if char in syn.words[0]:
                        banned = True
                        break
                if not banned:
                    synonym = syn.words[0]
                    if synonym is not None:
                        return synonym
        return None

    def get_pydict_syn(self, word, banned_chars):
        """Get synonym that does not contain any of banned_chars from PyDictionary. If no synonym found, returns None
		"""

        pydict_syns = self.dictionary.synonym(word)

        if pydict_syns is not None:
            for syn in pydict_syns:
                banned = False
                for char in banned_chars:
                    if char in syn:
                        banned = True
                        break
                if not banned:
                    synonym = syn
                    if synonym is not None:
                        return synonym
        return None
Ejemplo n.º 25
0
class Translator:
    def __init__(self):
        self.translator = tr()
        self.current_word_obj = ''
        self.dictionary = PyDictionary()

    def cldir(self, path):
        import os
        if os.listdir(path) != []:
            for item in os.listdir(path):
                os.remove(path + '/' + item)

    def word_checker(self, word):
        if self.dictionary.synonym(word) == None:
            return False
        return True

    def get_binary(self, word, source_='ru', destination_='en'):
        from_src_to_dest = GoogleTranslator(source=source_, target=destination_)
        self.cldir('cache')
        gTTS(text=from_src_to_dest.translate(word), lang=destination_).save('cache/word.wav')
        return open('cache/word.wav', 'rb').read()

    def create_object(self, id, word, source='ru', destination='en'):
        from_src_to_dest = GoogleTranslator(source=source, target=destination)
        from_dest_to_src = GoogleTranslator(source=destination, target=source)

        print(word, self.word_checker(word))
        #print(from_src_to_dest.translate(word), self.word_checker(from_src_to_dest.translate(word)))

        try:
            return {
            'is_learnt': False,
            'module': None,
            'teacher': None,
            'values': {
                'src': word.lower(),
                'dest': from_src_to_dest.translate(word).lower()
            },
            'languages': {
                'src': source,
                'dest': destination
            },
            'audio':
                {
                    'dest': self.get_binary(word, source_=source, destination_=destination) if word else None,
                    'src': self.get_binary(word, source_=destination, destination_=source) if word else None

                },
            'syntax': {
                'src': {
                    'part of speech': None if len(word_tokenize(word)) > 1 else (parts_of_speech[nltk.pos_tag(word_tokenize(word))[-1][1]] if source == 'en' else from_dest_to_src.translate(parts_of_speech[nltk.pos_tag(word_tokenize(from_src_to_dest.translate(word)))[-1][1]])),
                    'synonyms': None if len(word_tokenize(word)) > 1 or (not self.word_checker(word) and not self.word_checker(from_src_to_dest.translate(word))) else (self.dictionary.synonym(word)[:3] if source == 'en' else [from_dest_to_src.translate(el) for el in self.dictionary.synonym(from_src_to_dest.translate(word))[:3]])
                },
                'dest': {
                    'part of speech': None if len(word_tokenize(word)) > 1 else (parts_of_speech[nltk.pos_tag(word_tokenize(word))[-1][1]] if destination == 'en' else from_src_to_dest.translate(parts_of_speech[nltk.pos_tag(word_tokenize(from_dest_to_src.translate(word)))[-1][1]])),
                    'synonyms': None if len(word_tokenize(word)) > 1 or (not self.word_checker(word) and not self.word_checker(from_src_to_dest.translate(word))) else (self.dictionary.synonym(from_src_to_dest.translate(word))[:3] if destination == 'en' else [from_src_to_dest.translate(el) for el in self.dictionary.synonym(word)[:3]])
                }
            }
        }
        except:
            bot.send_message(id, 'text length need to be between 1 and 5000 characters')


    def send_word(self, message):

        # create inline keyboard
        add_to_vocab = types.InlineKeyboardMarkup()
        add_to_vocab.add(types.InlineKeyboardButton('add to vocabluary', callback_data='add_to_voc'))
        try:
            if TextBlob(message.text).detect_language() != 'en':
                print('185')
                #create word object
                word_obj = self.create_object(message.chat.id, message.text, source='ru', destination='en')

                print(db.is_unique(message.chat.id, message.text.lower()))
                self.current_word_obj = word_obj

                print(word_obj)

                # send translate
                bot.send_message(message.chat.id, word_obj['values']['dest'])

                #send pronunciation
                bot.send_voice(message.chat.id, word_obj['audio']['dest'], reply_markup=add_to_vocab)
            else:
                import datetime
                now = datetime.datetime.now()
                # create word object
                word_obj = self.create_object(message.chat.id, message.text, source='en', destination='ru')

                creating_time = datetime.datetime.now() - now
                print(creating_time)

                self.current_word_obj = word_obj

                #send translate
                bot.send_message(message.chat.id, word_obj['values']['dest'])

                #send pronunciation
                bot.send_voice(message.chat.id, word_obj['audio']['dest'], reply_markup=add_to_vocab)
        except Exception as e:
            print(e)
Ejemplo n.º 26
0
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)
Ejemplo n.º 27
0
    encoding='utf-8').read()

bunch = TextBlob(data)
find_good = bunch.sentences

# good_word_dict_1 = {}
# for d in dictionary.getSynonyms():
#     good_word_dict_1.update(d)

good_word_dict_2 = {}
ethical_list = open(
    "C:\\Users\\satvi\\Documents\\GitHub\\HIselector\\Satvik\\Bag of Words\\Ethical_words.txt"
).read().split("\n")
technical_list = ['deductible', 'copay', 'co-insurance']
for word in ['ethical', 'ethics', 'ethic']:
    ethical_list.extend(dictionary.synonym(word))
for word in ['technical', 'technology']:
    technical_list.extend(dictionary.synonym(word))
ethical_list = list(set(ethical_list))
technical_list = list(set(technical_list))

good_word_dict_2['ethical'] = ethical_list
good_word_dict_2['technical'] = technical_list

sentence_list = []
for sentence in find_good:
    sentence.strip()
    count = 0
    for category in good_word_dict_2:
        if (any(map(lambda word: word in sentence,
                    good_word_dict_2[category]))):
def getSyn(word):
    dic = PyDictionary()
    syn = dic.synonym(word)
    return syn
Ejemplo n.º 29
0
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")
Ejemplo n.º 30
0
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) + "*")
Ejemplo n.º 31
0
class ProcesareText:
    def __init__(self):
        # searchType (categoria din care face parte propozitia)
        self.searchType = None
        # inputType (tipul propozitiei)
        self.inputType = None
        # keyWords de forma [[(cuvant cheie, sinonim),(cuvant cheie, sinonim)],[Subiect1, Subiect2, ...]]
        self.keyWords = list()
        # full text
        self.filters = [
            'YesOrNo', 'DifferenceBetween', 'PersonalQuestion', 'MathQuestion',
            'ChooseBetween', 'InfoAbout'
        ]
        # anaphora
        self.Subjects = list()
        self.PRP = [('it', 'he', 'she', 'him', 'her'),
                    ('we', 'they', 'us', 'them')]
        self.PRPP = [('his', 'her', 'its', 'hers'), ('our', 'their')]
        # train to classify Question
        self.filters = [
            'OpinionQuestion', 'YesOrNo', 'DifferenceBetween',
            'PersonalQuestion', 'MathQuestion', 'ChooseBetween', 'InfoAbout'
        ]
        self.dictionary = PyDictionary()

        #train to classify Question
        self._setQuestionWorld()

    def changeAnaphoraSubjects(self):
        self.Subjects = self.getAllTags('NNP')

    def setAnaphoraSubjects(self):
        if self.Subjects:
            for i in xrange(len(self.posTag)):
                if self.posTag[i][1] == 'PRP':
                    if (self.posTag[i][0].lower() in self.PRP[0]) and len(
                            self.Subjects[0]) == 1:
                        self.text = self.text.replace(self.posTag[i][0],
                                                      self.Subjects[0][0], 1)
                        self.posTag[i] = tuple(
                            [self.Subjects[0][0], self.Subjects[1]])
                    elif (self.posTag[i][0].lower()
                          in self.PRP[1]) and len(self.Subjects[0]) > 1:
                        posTag = self.posTag[i][0]
                        self.posTag[i] = tuple(
                            [self.Subjects[0][0], self.Subjects[1]])
                        subjects = self.Subjects[0][0]
                        for subject in self.Subjects[0][1:]:
                            self.posTag.insert(
                                i, tuple([subject, self.Subjects[1]]))
                            subjects += ', ' + subject
                        self.text = self.text.replace(posTag, subjects, 1)
                elif self.posTag[i][1] == 'PRP$':
                    if (self.posTag[i][0].lower() in self.PRPP[0]) and len(
                            self.Subjects[0]) == 1:
                        subject = self.Subjects[0][0] + "'s"
                        self.text = self.text.replace(self.posTag[i][0],
                                                      subject, 1)
                        self.posTag[i] = tuple([subject, self.Subjects[1]])
                    elif (self.posTag[i][0].lower()
                          in self.PRPP[1]) and len(self.Subjects[0]) > 1:
                        posTag = self.posTag[i][0]
                        self.posTag[i] = tuple(
                            [self.Subjects[0][0], self.Subjects[1]])
                        subjects = self.Subjects[0][0] + "'s"
                        for subject in self.Subjects[0][1:]:
                            self.posTag.insert(
                                i, tuple([subject, self.Subjects[1]]))
                            subjects += ", " + subject + "'s"
                        self.text = self.text.replace(posTag, subjects, 1)
        self.changeAnaphoraSubjects()

    def _clearParam(self):
        self.originaltext = None
        self.text = None
        self.searchType = None
        self.inputType = None
        self.keyWords = list()

    def setText(self, text):
        self._clearParam()
        self.originaltext = text
        self.text = self.errorSyntaxText(text)
        self.setTags()

    def _setQuestionWorld(self):
        self.dictionary = PyDictionary()
        posts = nchat.xml_posts()[:10000]
        featuresets = [(self.dialogue_act_features(post.text),
                        post.get('class')) for post in posts]
        size = int(len(featuresets) * 0.1)
        train_set, test_set = featuresets[size:], featuresets[:size]
        self.classifier = nltk.NaiveBayesClassifier.train(train_set)
        self.classifier.labels()

    def dialogue_act_features(self, post):
        features = {}
        for word in nltk.word_tokenize(post):
            features['contains(%s)' % word.lower()] = True
        return features

    def classify_sentence(self, sentence):
        final_test_sentence = self.dialogue_act_features(sentence)
        result = self.classifier.classify(final_test_sentence)
        if (result == "whQuestion") or (result == "ynQuestion"):
            return True
        else:
            return False

    # se scot semnele de punctuatie
    def errorSyntaxText(self, text):
        listp = [',', '.', ';', '?', '!', '"', ":"]
        for p in listp:
            text = text.replace(p, ' ')
        return text

    def setTags(self):
        # fiecare cuvant din propozitie cu partea s-a de vorbire (NN-subiect,...)
        self.posTag = pos_tag(word_tokenize(self.text))
        # self.poSentenceTag = pos_tag(sentence_tokenize(self.text))

    def getSynonym(self, word):
        listSynonyms = self.dictionary.synonym(self.errorSyntaxText(word))
        if listSynonyms:
            return random.choice(listSynonyms)

    # index reprezinta pozitia de unde incepe cautarea unui cuvant cu partea de vorbire ce se gaseste in whatIs
    # in caz de sunt mai multe una dupa alta se va returna ultimul cuvant
    # Functie creata pentru PesonalQuestion
    def getNextTag(self, index, whatIs):
        try:
            i = index
            while (i < len(self.posTag)):
                i += 1
                tag = self.posTag[i]
                if tag[1] in whatIs:
                    i += 1
                    while (i < len(self.posTag)):
                        if self.posTag[i] not in whatIs:
                            break
                        else:
                            tag = self.posTag[i]
                            i += 1
                    return tag
            return None
        except Exception:
            return None

    def getNextStructureTag(self, index, whatIs, direction=1):
        try:
            i = index
            while (i < len(self.posTag) and i > -1):
                i += direction
                tag = list(self.posTag[i])
                if self.posTag[i][1] in whatIs:
                    i += direction
                    while (i < len(self.posTag) and i > -1):
                        if self.posTag[i][1] not in whatIs:
                            return tuple(tag)
                        tag[0] += self.posTag[i][0]
                        i += direction
                    return tuple(tag)
            return None
        except Exception:
            return None

    def getAllTags(self, whatIs):
        allTags = list()
        for tag in self.posTag:
            if tag[1] == whatIs:
                allTags.append(tag[0])
        return [allTags, whatIs]

    def findStrings(self, stringsList):
        for i in xrange(len(self.posTag)):
            if self.posTag[i][0].lower() in stringsList:
                return i + 1
        return 0

    def _setkeyWordsCriteriu(self, criteriu):
        try:
            if type(self.keyWords[0]) == list:
                pass
            elif type(self.keyWords[0] != list):
                self.keyWords[0] = list()
        except Exception:
            self.keyWords.append(list())
        self.keyWords[0].append((criteriu, str(self.getSynonym(criteriu))))

    def _setkeyWordsSubiecti(self, listaSubiecti):
        try:
            if type(self.keyWords[1]) == list:
                pass
            elif type(self.keyWords[1] != list):
                self.keyWords[1] = list()
        except Exception:
            while (len(self.keyWords) < 2):
                self.keyWords.append(list())

        # if type(listaSubiecti) is list:
        #     for subiect in listaSubiecti:
        #         self.keyWords[1].append(subiect)
        # else:
            self.keyWords[1].append(listaSubiecti)

    #tag[0] - life
    #tag[1] - NN
    def PersonalQuestion(self):
        if self.findStrings(['your', 'about']):
            # Tell me your name.
            # What is your name?
            # Is Cata your name?
            # What about your name?
            # Tell me one of your favorite movie.
            index = self.findStrings(['your', 'about']) - 1
            nextTag = self.getNextStructureTag(index, ['NN', 'NNP'])
            if nextTag is not None:
                if self.findStrings(['tell', 'what', 'who']):
                    self._setkeyWordsCriteriu(nextTag[0])
                    if self.findStrings(['about']):
                        i = self.findStrings(['about']) - 1
                        self._setkeyWordsSubiecti(
                            [self.getNextStructureTag(i, ['NN', 'NNP'])])
                    return True
                elif self.findStrings(['where']):
                    self._setkeyWordsCriteriu('location')
                    self._setkeyWordsCriteriu(nextTag[0])
                    return True
                elif self.findStrings(['when']):
                    self._setkeyWordsCriteriu('time')
                    self._setkeyWordsCriteriu(nextTag[0])
                    return True
                elif self.findStrings(['why']):
                    self._setkeyWordsCriteriu('opinion')
                    self._setkeyWordsCriteriu(nextTag[0])
                    return True
                elif self.findStrings(['is']):
                    i = self.findStrings(['is']) - 1
                    if i > 0 and (self.posTag[i - 1][1] == 'NN'
                                  or self.posTag[i - 1][1] == 'NNP'
                                  or self.posTag[i - 1][1] == 'JJ'):
                        self._setkeyWordsCriteriu(nextTag[0])
                        self._setkeyWordsSubiecti([
                            self.posTag[i - 1][0],
                        ])
                        return True
                    elif i < len(self.posTag) - 1 and (
                            self.posTag[i + 1][1] == 'NN'
                            or self.posTag[i + 1][1] == 'NNP'
                            or self.posTag[i + 1][1] == 'JJ'):
                        self._setkeyWordsCriteriu(nextTag[0])
                        self._setkeyWordsSubiecti([
                            self.posTag[i + 1][0],
                        ])
                        return True
                elif self.findStrings(['do']):
                    self._setkeyWordsCriteriu(nextTag[0])
                    return True
        elif self.findStrings(['you']):
            index = self.findStrings(['you']) - 1
            if self.findStrings(['what']):
                nexTag = self.getNextStructureTag(index, 'VB')
                if nexTag is not None:
                    self._setkeyWordsCriteriu(nexTag[0])
                    nextTag = self.getNextStructureTag(index,
                                                       ['NN', 'NNS', 'NNP'])
                    if nextTag is not None:
                        self._setkeyWordsSubiecti([nextTag[0]])
                    else:
                        nextTag = self.getNextStructureTag(
                            index, ['NN', 'NNS', 'NNP'], direction=-1)
                        if nextTag is not None:
                            self._setkeyWordsSubiecti([nextTag[0]])
                    return True
            elif self.findStrings(['who']):
                if self.findStrings(['are']):
                    self._setkeyWordsCriteriu('identity')
                    return True
            elif self.findStrings(['where']):
                nextTag = self.getNextStructureTag(index, ['VB', 'VBG', 'IN'])
                if nextTag[0] is not None:
                    self._setkeyWordsCriteriu('location')
                    self._setkeyWordsCriteriu(nextTag[0])
                    return True
                elif nextTag[1] == 'VB' or nextTag[1] == 'VBG':
                    self._setkeyWordsCriteriu(nextTag[0])
                    return True
            elif self.findStrings(['why']):
                self._setkeyWordsCriteriu('opinion')
                nexTag = self.getNextStructureTag(index, ['VB', 'IN'])
                if nexTag is not None:
                    self._setkeyWordsCriteriu(nexTag[0])
                    nextTag = self.getNextStructureTag(index,
                                                       ['NN', 'NNS', 'NNP'])
                    if nextTag is not None:
                        self._setkeyWordsSubiecti([nextTag[0]])
                    else:
                        nextTag = self.getNextStructureTag(
                            index, ['NN', 'NNS', 'NNP'], direction=-1)
                        if nextTag is not None:
                            self._setkeyWordsSubiecti([nextTag[0]])
                    return True
            elif self.findStrings(['how']):
                if self.findStrings(['old']):
                    self._setkeyWordsCriteriu('age')
                    return True
                nextTag = self.getNextStructureTag(index, ['NN', 'NNS', 'NNP'],
                                                   direction=-1)
                if nextTag is not None:
                    self._setkeyWordsCriteriu(nextTag[0])
                    return True
            elif self.findStrings(['like', 'have', 'work']):
                nexTag = self.getNextStructureTag(index, 'VB')
                if nexTag is not None:
                    self._setkeyWordsCriteriu(nexTag[0])
                    nextTag = self.getNextStructureTag(index,
                                                       ['NN', 'NNS', 'NNP'])
                    if nextTag is not None:
                        self._setkeyWordsSubiecti([nextTag[0]])
                    else:
                        nextTag = self.getNextStructureTag(
                            index, ['NN', 'NNS', 'NNP'], direction=-1)
                        if nextTag is not None:
                            self._setkeyWordsSubiecti([nextTag[0]])
                    return True
            elif (index > 0 and self.posTag[index - 1][0]
                  == 'are') or (index < len(self.posTag) - 1
                                and self.posTag[index + 1][0] == 'are'):
                nextTag = self.getNextStructureTag(index, 'JJ')
                if nextTag is not None:
                    self._setkeyWordsCriteriu('compliment')
                    self._setkeyWordsCriteriu(nextTag[0])
                    return True
        return False

    ####### START INFO ABOUT #######
    def _getSubjectList(self, start, end):
        try:
            result = list()
            for tags in xrange(start, end):
                if self.posTag[tags][1] not in [
                        'VBZ', 'VBD', 'VBN', 'VBP', 'IN', 'DT', 'WP', 'WDT',
                        'WRB', 'CC'
                ] and self.posTag[tags][0].lower() != "which":
                    result.append(self.posTag[tags][0])
            return result
        except:
            return None

    def _getCriteria(self, start, end):
        try:
            result = ""
            for tags in xrange(start, end):
                if self.posTag[tags][1] in ['VBZ', 'VBD', 'VBN', 'VBP']:
                    result += self.posTag[tags][0]
                    result += " "
            return result
        except:
            return None

    def ChooseBetween(self):
        for index in xrange(len(self.posTag)):
            # Who is older? Obama, Putin, Merkel or Churchill?
            # Who is older between Obama, Putin, Merkel and Churchill?
            # Which is solid between rock and vodka?
            if self.posTag[index][1] == 'VBZ' and self.posTag[index][
                    0] == 'is' and self.posTag[index + 1][1] in ['JJR', 'JJ']:
                nextTag = self.getNextTag(index, ['JJR', 'JJ'])
                if nextTag is not None:
                    self._setkeyWordsCriteriu(nextTag[0])
                    i = index
                    leng = len(self.posTag)
                    while i < leng:
                        i += 1
                        nextTag = self.getNextTag(i, ['NNP', 'IN', 'CC', 'NN'])
                        if nextTag is not None:
                            if nextTag[1] not in ['NNP', 'NN']:
                                leng -= 1
                            else:
                                self._setkeyWordsSubiecti(nextTag[0])
                return True

            # Who has more/less
            elif self.posTag[index][1] == 'VBZ' and self.posTag[index][
                    0].lower() == 'has' and self.posTag[index +
                                                        1][1] in ['JJR', 'JJ']:
                nextTag = self.getNextTag(index, ['JJR', 'JJ'])
                if nextTag is not None:
                    if nextTag[0] in ['more', 'less', 'fewer', 'greater']:
                        self._setkeyWordsCriteriu(nextTag[0])
                        noun = self.getNextTag(index + 1, ['NN', 'NNS', 'JJ'])
                        self._setkeyWordsCriteriu(noun[0])
                    i = index + 1
                    leng = len(self.posTag)
                    while i < leng:
                        i += 1
                        nextTag = self.getNextTag(i, ['NNP', 'IN', 'CC', 'NN'])
                        if nextTag is not None:
                            if nextTag[1] not in ['NNP', 'NN']:
                                leng -= 1
                            else:
                                self._setkeyWordsSubiecti(nextTag[0])
                return True
        return False

    def MathQuestion(self):
        for index in xrange(len(self.posTag)):
            # What is the root of the (equation)..? ex:2*x+4=0
            if self.posTag[index][1] == 'NN' and self.posTag[index][0].lower(
            ) == 'root':
                nextTag = self.getNextTag(index, ['NN'])
                if nextTag != None:
                    if (nextTag[0] == 'equation'):
                        self._setkeyWordsCriteriu('root of equation')
                        listaSubiecti = []
                        subiect = self.getNextTag(index, ['CD'])
                        subiect = subiect[0]
                        listaSubiecti.append(subiect)
                        self._setkeyWordsSubiecti(listaSubiecti)
                        subiect = self.getNextTag(index, ['CD'])
                        subiect = subiect[0]
                        self._setkeyWordsSubiecti(subiect)
                        return True

            # pentru operatii matematice simple formate doar din 2 termeni (ex:What is the result of the 9+7?
            if self.posTag[index][1] == 'NN' and self.posTag[index][0].lower(
            ) == 'result':
                nextTag = self.getNextTag(index, ['IN'])
                if nextTag != None:
                    if (nextTag[0] == 'of'):
                        self._setkeyWordsCriteriu(
                            'result of arithmetic operation')
                        subiect = self.getNextTag(index, ['CD'])
                        subiect = subiect[0]
                        self._setkeyWordsSubiecti(subiect)
                        return True
            # What is the value of PI?
            if self.posTag[index][1] == 'IN' and self.posTag[index][0].lower(
            ) == 'of':
                nextTag = self.getNextTag(index, ['NNP'])
                if nextTag != None:
                    if (nextTag[0].lower() == 'pi'):
                        self._setkeyWordsCriteriu('value of pi')
                        listaSubiecti = []
                        subiect = self.getNextTag(index, ['NNP'])
                        subiect = subiect[0]
                        listaSubiecti.append(subiect)
                        self._setkeyWordsSubiecti(listaSubiecti)
                        subiect = self.getNextTag(index, ['NNP'])
                        subiect = subiect[0]
                        self._setkeyWordsSubiecti(subiect)
                        return True
            # What is the integral of ...?
            if self.posTag[index][1] == 'JJ' and self.posTag[index][0].lower(
            ) == 'integral':
                nextTag = self.getNextTag(index, ['CD'])
                if nextTag != None:
                    self._setkeyWordsCriteriu('integral of')
                    subiect = self.getNextTag(index, ['CD'])
                    subiect = subiect[0]
                    self._setkeyWordsSubiecti(subiect)
                    return True
            # What is half of x?
            if self.posTag[index][1] == 'NN' and self.posTag[index][0].lower(
            ) == 'half':
                nextTag = self.getNextTag(index, ['CD'])
                if nextTag != None:
                    self._setkeyWordsCriteriu('half of')
                    subiect = self.getNextTag(index, ['CD'])
                    subiect = subiect[0]
                    self._setkeyWordsSubiecti(subiect)
                    return True
            # What is sqrt/radical of x?
            if self.posTag[index][1] == 'NN' and self.posTag[index][0].lower() == 'sqrt' or \
                            self.posTag[index][0].lower() == 'radical':
                nextTag = self.getNextTag(index, ['CD'])
                if nextTag != None:
                    self._setkeyWordsCriteriu('sqrt of')
                    subiect = self.getNextTag(index, ['CD'])
                    subiect = subiect[0]
                    self._setkeyWordsSubiecti(subiect)
                    return True
            # What number comes after x?
            if self.posTag[index][1] == 'NN' and self.posTag[index][0].lower(
            ) == 'number':
                nextTag = self.getNextTag(index, ['IN'])
                if nextTag != None:
                    if (nextTag[0].lower() == 'after'):
                        self._setkeyWordsCriteriu('number after x')
                        listaSubiecti = []
                        subiect = self.getNextTag(index, ['CD'])
                        subiect = self.getNextTag(index, ['NN'])
                        subiect = subiect[0]
                        self._setkeyWordsSubiecti(subiect)
                        return True
            # What number comes before x?
            if self.posTag[index][1] == 'NN' and self.posTag[index][0].lower(
            ) == 'number':
                nextTag = self.getNextTag(index, ['IN'])
                if nextTag != None:
                    if (nextTag[0].lower() == 'before'):
                        self._setkeyWordsCriteriu('number before x')
                        listaSubiecti = []
                        subiect = self.getNextTag(index, ['CD'])
                        subiect = self.getNextTag(index, ['NN'])
                        subiect = subiect[0]
                        self._setkeyWordsSubiecti(subiect)
                        return True
        return False

    def InfoAbout(self):
        if self.searchType is not None:
            return False

        for index in xrange(len(self.posTag)):
            if self.posTag[index][1] == 'WP' and self.posTag[index][0].lower(
            ) in ['what', 'who']:
                # What is onion?
                # Who won six consecutive Wimbledon singles titles in the 1980s?
                nextTag = self._getCriteria(0, len(self.posTag))
                if nextTag is not None or nextTag != "":
                    nextNextTag = self._getSubjectList(0, len(self.posTag))
                    if nextNextTag is not None:
                        self._setkeyWordsCriteriu(nextTag)
                        self._setkeyWordsSubiecti(nextNextTag)
                        return True

            elif self.posTag[index][1] == 'WRB' and self.posTag[index][
                    0].lower() in ['where', 'how', 'why']:
                # Where is/was ... ?
                # How many arms/tentacles/limbs does a squid have?
                nextTag = self._getCriteria(0, len(self.posTag))
                if nextTag is not None or nextTag != "":
                    nextNextTag = self._getSubjectList(0, len(self.posTag))
                    if nextNextTag is not None:
                        if self.posTag[index][0].lower() == 'where':
                            self._setkeyWordsCriteriu('location')
                        if self.posTag[index][0].lower() == 'why':
                            self._setkeyWordsCriteriu('reason')
                        self._setkeyWordsCriteriu(nextTag)
                        self._setkeyWordsSubiecti(nextNextTag)
                        return True

            elif self.posTag[index][1] in [
                    'WDT', 'JJ', 'NNP'
            ] and self.posTag[index][0].lower() in ['which']:
                # Which hills divide England from Scotland?
                nextTag = self._getCriteria(0, len(self.posTag))
                if nextTag is not None or nextTag != "":
                    nextNextTag = self._getSubjectList(0, len(self.posTag))
                    if nextNextTag is not None:
                        self._setkeyWordsCriteriu(nextTag)
                        self._setkeyWordsSubiecti(nextNextTag)
                        return True
        return False

    ####### END INFO ABOUT #######

    def setFilter(self):
        for filterName in self.filters:
            filterWasImported = filterName in globals()
            if filterWasImported:
                f = globals()[filterName]
                r, v = f(self.text, self.posTag)
                if r:
                    self.searchType = filterName
                    #self.searchType = self.filters.index(filterName)
                    for item in v['criterii']:
                        self._setkeyWordsCriteriu(item)
                    for item in v['subiecti']:
                        self._setkeyWordsSubiecti(item)
                    break
            else:
                r = getattr(self, filterName, lambda: False)()
                if r:
                    self.searchType = filterName
                    #self.searchType = self.filters.index(filterName)
                    break

    def setInputType(self):
        self.inputType = self.classify_sentence(self.text)
Ejemplo n.º 32
0
    elif('divide') in response :
        input = response
        (a,b,c,d) =[t(s) for t,s in zip((str,int,str,int),re.search('^(\w+) (\d+) (\w+) (\d+)$',input).groups())]
        result = float(b/d)

        print(result)


    elif('define') in response:

        query = response
        stopwords = ['define']
        querywords = query.split()
        resultwords  = [word for word in querywords if word.lower() not in stopwords]
        result = ''.join(resultwords)
        rand = (dictionary.synonym(result))
        print(rand)


    elif('tell me a joke')in response:
        rand=(pyjokes.get_joke())
        print(rand)







    elif response == ("do you have a brother"):
        print("yes")
Ejemplo n.º 33
0

# However, this becomes tedious if we want to keep adding additional keywords such as 'aircraft'.  
# A better approach is to, for example, include synonyms for the word 'airplane'.  
# 
# We can do this using one of the above libraries but we could also use `PyDictionary`, `pip install PyDictionary`

# In[39]:

from PyDictionary import PyDictionary
dictionary=PyDictionary()


# In[40]:

print(dictionary.synonym('airplane'))


# In[41]:

plane_words = dictionary.synonym('airplane') + ['airplane', 'flight']


# In[42]:

for x in submission_titles:
    if 'egypt' in x.lower():
        if any(word in x.lower() for word in plane_words):
            print(x)

Ejemplo n.º 34
0
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())
import twitter
#put all your special keys here
api = twitter.Api(consumer_key='',
                      consumer_secret='',
                      access_token_key='',
                      access_token_secret='')


printout = ""
#list of games
gamelist = ['Call of* Duty :* Advanced Warfare', 'The* Elder Scrolls IV:* Oblivion', 'Half Life 2', 'Faster Than* Light', 'Empire :* Total War', 'Call of* Cthulhu:* Dark Corners of* the* Earth', 'Kerbal* Space Program', 'Splinter Cell :* Chaos Theory', 'The* Curse of* Monkey Island', 'Operation Flashpoint :* Cold War Crisis', 'Company of* Heroes 2*', 'Mass Effect 2*', 'Thief II:* The* Metal Age', 'The* Last of* Us', 'Metal Gear Solid 4:* Guns of* the* Patriots', 'Street Fighter II*', 'Dragon Age :* Inquisition', 'The* Legend of* Zelda:* Ocarina* of* Time', 'Red Dead Redemption', 'Time Splitters :* Future Perfect', 'Uncharted 2:* Among Theives', 'Grand Theft Auto :* Vice City', 'Unreal Tournament', 'Middle earth :* Shadow of Mordor*', 'God of* War', 'Rollercoaster Tycoon', 'Mine Craft', 'World of* War Craft', 'League of* Legends', 'Mount and* Blade :* War band', 'System Shock 2*', 'Team Fortress 2*', 'Alien :* Isolation', 'Hit Man :* Blood Money', 'Star Wars :* Knights Of* The* Old Republic', 'Tony* Hawk \'s* Pro Skater 2*', 'Tony* Hawk \'s* Pro Skater 3*', 'Perfect Dark', 'Metroid* Prime', 'Halo:* Combat Evolved', 'Out of* the* Park Baseball 2007*', 'Resident Evil 4*', 'Mass Effect 2*', 'Baldur\'s* Gate II:* Shadows of Amn*', 'Little Big Planet', 'World of Goo', 'Bio Shock Infinite', 'Final Fantasy IX*', 'Devil May Cry', 'Civilization IV*', 'Quake', 'Ninja Gaiden* Black', 'Jet Grind Radio', 'Burnout 3:* Takedown']
#splits a random game from the list and puts the words in another list
splitlist = gamelist[randint(0, (len(gamelist)-1))].split()
for i in range(0, (len(splitlist))):
#here you take each word, get a list of synonyms, choose a random one
	synonym = dictionary.synonym(splitlist[i])
#if the word has a * at the end, it is preserved	
	if splitlist[i][-1] == '*':
	    printout = printout + " " + splitlist[i][:len(splitlist[i])-1]
#if there are no synonyms, the word is preserved
	elif len(synonym) is True:
		printout = printout + " " + splitlist[i]
#random synonym is chosen	
	else:
		printout = printout + " " + synonym[randint(0, (len(synonym)-1))]
#reformats the colons
printout = printout.replace(' :', ':')
#capitalises the words
status = api.PostUpdate(printout.title())
print status.text
Ejemplo n.º 36
0
    "Natural", "Flood", "Buildings", "Malls", "Government", "Lack of Funding",
    "Military", "Petitions", "Politics", "Census", "Constitution",
    "Corruption", "Home", "Museum", "Relgious Institution", "Synagogue",
    "Cemetary", "Church", "Cathedral", "Mosque", "War-Torn", "Past", "Present",
    "Future", "Hope", "Religion", "Religious Symbol", "Absence",
    "Gender Inequality", "Careers", "Nepotism"
]
#print(len(keywords_and_phrases))
f = open("most-frequently-used-words.txt")
s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)

for i in range(len(keywords_and_phrases)):
    print(len(keywords_and_phrases))
    new_list = []
    try:
        new_list = dictionary.synonym(keywords_and_phrases[i])
        if len(new_list) > 0:
            for j in range(len(new_list)):
                if (new_list[j] not in keywords_and_phrases
                        and new_list[j].title() not in keywords_and_phrases and
                    (s.find(bytes(new_list[j].lower(), encoding='utf-8'))
                     == -1)):
                    keywords_and_phrases.append(new_list[j].title())
    except TypeError:
        pass

f.close()

keywords = open('Keywords_And_Phrases.csv', 'w')
for i in range(len(keywords_and_phrases)):
    keywords.write(keywords_and_phrases[i] + ',' + '\n')
Ejemplo n.º 37
0
# -- coding: utf-8 --

from PyDictionary import PyDictionary

import random

dictionary = PyDictionary()

frost = [
    'Two', 'roads', 'diverged', 'in', 'a', 'wood', ',', 'and', 'I', ',', 'I',
    'took', 'the', 'one', 'less', 'traveled', 'by', 'and', 'that', 'has',
    'made', 'all', 'the', 'difference'
]

print random.choice((dictionary.synonym(frost[0]))) + " " + random.choice(
    (dictionary.synonym(frost[1]))) + " " + random.choice((dictionary.synonym(
        frost[2]))) + " " + frost[3] + " " + frost[4] + " " + random.choice(
            (dictionary.synonym(frost[5]))) + ","
Ejemplo n.º 38
0

#parsing
synPhrase = ""
quotesTxt = open('synPhrase_quotes.txt', 'r')
lineParse = quotesTxt.read().split("\n")
quotesOnly = lineParse[::3]

#cycling through each quote and parsing each by word
for x in range(0, (len(quotesOnly))):
	cleanser = quotesOnly[x].lower().replace('.','').replace(',','').replace(';','')
	wordParse = cleanser.split(" ")
	
	#finding synonyms for each word
	for i in range(0, (len(wordParse))):	
		synonyms = dictionary.synonym(wordParse[i])
		if wordParse[i] == 'the' or wordParse[i] == "it's" or wordParse[i] == "isn't" or wordParse[i] == 'to' or wordParse[i] == 'an' or wordParse[i] == 'your' or wordParse[i] == 'is' or wordParse[i] == 'about' or wordParse[i] == 'not' or wordParse[i] == 'a'  or wordParse[i] == 'it'  or wordParse[i] == 'of'  or wordParse[i] == 'and' or wordParse[i] == 'but' or wordParse[i] == 'into' or wordParse[i] == 'in' or wordParse[i] == 'only' or wordParse[i] == 'at' or wordParse[i] == 'any' or wordParse[i] == 'you' or wordParse[i] == 'are' or wordParse[i] == 'does' or wordParse[i] == "don't" or wordParse[i] == "doesn't" or wordParse[i] == "can't" or wordParse[i] == 'are' or wordParse[i] == "you're":
			synPhrase = synPhrase + " " + wordParse[i]
		else:
			synPhrase = synPhrase + " " + synonyms[0]	



		# if wordParse[i] == 'the' or wordParse[i] == "it's" or wordParse[i] == "isn't" or wordParse[i] == 'to' or wordParse[i] == 'an' or wordParse[i] == 'your' or wordParse[i] == 'is' or wordParse[i] == 'about' or wordParse[i] == 'not' or wordParse[i] == 'a'  or wordParse[i] == 'it'  or wordParse[i] == 'of'  or wordParse[i] == 'and' or wordParse[i] == 'but' or wordParse[i] == 'into' or wordParse[i] == 'in' or wordParse[i] == 'only' or wordParse[i] == 'at' or wordParse[i] == 'any' or wordParse[i] == 'you' or wordParse[i] == 'are' or wordParse[i] == 'does' or wordParse[i] == "don't" or wordParse[i] == "doesn't" or wordParse[i] == "can't" or wordParse[i] == 'are' or wordParse[i] == "you're" :
		# 	synPhrase = synPhrase + " " + wordParse[i]		
		# else: 
		# 	synonyms = dictionary.synonym(wordParse[i])
		# 	synPhrase = synPhrase + " " + synonyms[0]


Ejemplo n.º 39
0
        #logic for execution based on query
        if 'wikipedia' in query:
            speak("Searching Wikipedia...")
            query = query.replace("wikipedia","")
            results = wikipedia.summary(query,sentences=2)
            speak("According to wikipedia")
            print(results)
            speak(results)

        elif 'meaning of' in query:
            query=query.replace("meaning of","")
            print (dictionary.meaning(query))

        elif 'synonym of' in query:
            query=query.replace("synonym of","")
            print (dictionary.synonym(query))
        
        elif 'antonym of' in query:
            query=query.replace("antonym of","")
            print (dictionary.antonym(query))
        
        elif 'open youtube' in query:
            webbrowser.open("youtube.com")

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

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

        elif 'play music' in query:
Ejemplo n.º 40
0
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()
Ejemplo n.º 41
0
async def on_message(message):
    tempMessage = 0
    error = ""

    if message.content.startswith("//"):
        await client.send_typing(message.channel)
        message = message
        await client.delete_message(message)

        if message.author.top_role.name == "No Bot":
            error = "You have been banned from using the bot."
            tempMessage = 5
            msg = await client.send_message(message.channel, ":no_entry_sign: " + message.author.mention + ", " + error)
            await asyncio.sleep(tempMessage)
            await client.delete_message(msg)
            return

        elif message.content.startswith("//editme"):
            msg = await client.send_message(message.author, "10")
            await asyncio.sleep(3)
            await client.edit_message(msg, "40")

        # we do not want the bot to reply to itself
        elif message.author == client.user:
            return

        if message.content.startswith("//hello"):
            msg = "Hello " + message.author.mention
            await client.send_message(message.channel, msg, tts=True)

        elif message.content.startswith("//ask"):
            if message.author.top_role.name == "Admin":
                adminState = True
            else:
                adminState = False
            if "?" not in message.content:
                await client.send_message(message.channel, "**Question: **" + str((message.content[6:] + "?").capitalize()) + " **Response:** " + AI.answer(message.content[6:],adminState))
            else:
                await client.send_message(message.channel, "**Question: **" + str((message.content[6:]).capitalize()) + " **Response:** " + AI.answer(message.content[6:],adminState))

        #elif message.content.startswith("//chat"):
        #    await client.send_message(message.channel, message.author.mention + ": " + str((message.content[7:]).capitalize()) + "\n" +
        #    str(ChatBot.talk(message.content[7:])).capitalize())

        elif message.content.startswith("//petition"):
            votes = 7
            if len(message.content[11:]) != 0:
                msg = await client.send_message(message.channel, ":ballot_box_with_check: Petition: **" + message.content[11:] + "** - created by: " + message.author.mention + ". React with thumbs on this message to vote @here! (" + str(votes) + " votes to pass or fail)")
                await client.add_reaction(msg, "\U0001F44D")
                await client.add_reaction(msg, "\U0001F44E")
                count = [0,0]
                #[upvotes,downvotes]
                alreadyVoted = [[],[]]
                upvotedDisplay = await client.send_message(message.channel, "**0** \U0001F44D")
                downvotedDisplay = await client.send_message(message.channel, "**0** \U0001F44E")
                await asyncio.sleep(1)
                while count[0] <= votes - 1 and count[1] <= votes - 1:
                    res = await client.wait_for_reaction(message=msg)
                    if res.user != client.user:
                        await client.remove_reaction(msg, res.reaction.emoji, res.user)
                    if (res.user not in alreadyVoted[0]) and (res.user not in alreadyVoted[1]) and (res.user != client.user):
                        if res.reaction.emoji == "\U0001F44D":
                            count[0] += 1
                            alreadyVoted[0].append(res.user)
                        if res.reaction.emoji == "\U0001F44E": 
                            count[1] += 1
                            alreadyVoted[1].append(res.user)
                        displayVotedUp = ', '.join(str(votee) for votee in alreadyVoted[0])
                        await client.edit_message(upvotedDisplay, "**" + str(len(alreadyVoted[0])) + "** \U0001F44D " + displayVotedUp)
                        displayVotedDown = ', '.join(str(votee) for votee in alreadyVoted[1])
                        await client.edit_message(downvotedDisplay, "**" + str(len(alreadyVoted[1])) + "** \U0001F44E " + displayVotedDown)
                if count[0] >= votes:
                    await client.send_message(message.channel, ":ballot_box_with_check: Voting done! - sent to an admin for review.")
                    adminChannel = client.get_channel("256589191444430848")
                    await client.send_message(adminChannel,  ":ballot_box_with_check: Petition created by: " + message.author.mention + " passed voting! - **" + message.content[11:] + "**")
                else:
                    await client.send_message(message.channel, ":x: Voting failed!") 
            else:
                msg = await client.send_message(message.channel, "Please enter something into the petition.")
                await asyncio.sleep(5)
                await client.delete_message(msg)

        elif message.content.startswith("//vote"):
            #http://discordpy.readthedocs.io/en/latest/api.html#discord.Client.get_reaction_users
            voteEmoticion = "\u2714"
            unvoteEmoticon = "\u2716"
            if len(message.content[7:]) != 0:
                msg = await client.send_message(message.channel, ":ballot_box_with_check: Vote: **" + message.content[7:] + "** - created by: " + message.author.mention + ". @here, Click vote reactions to vote!")
                await asyncio.sleep(0.5)
                await client.add_reaction(msg, voteEmoticion)
                await client.add_reaction(msg, unvoteEmoticon)
            else:
                msg = await client.send_message(message.channel, ":no_entry_sign: " + message.author.mention + ", Please enter something into the vote.")
                await asyncio.sleep(5)
                await client.delete_message(msg)

        elif message.content.startswith("//deleteme"):
            tempMessage = 0.1
            msg = await client.send_message(message.channel, "You saw nothin.")

        elif message.content.startswith("//roll"):
            limit = int(message.content[6:])
            result = str(random.randint(1, limit))
            msg = await client.send_message(message.channel, result)
            tempMessage = 5

        elif message.content.startswith("//help detail"):
            await client.send_message(message.channel, helpText.help() + version + "\n" + message.author.mention)

        elif message.content.startswith("//help"):
            await client.send_message(message.channel, helpText.helpSimple() + version + "\n" + message.author.mention)

        elif message.content.startswith("//choose"):
            if len(message.content[9:]) == 0:
                error = "Invalid format! //choose <option 1 2 3...>"
                tempMessage = 5
                return
            else:
                given = message.content[9:]
                choices = given.split(", ")
                msg = await client.send_message(message.channel, "Options:" + message.content[8:] + ", I have chosen: **" + random.choice(choices) + "**")

        elif message.content.startswith("//salt" or "//salty"):
            msg = await client.send_file(message.channel, "salt.png")
            tempMessage = 30

        elif message.content.startswith("//wiki"):
            try:
                page = wikipedia.page(message.content[7:])
                emb = discord.Embed()
                emb.title = ":newspaper: " + str(page.title)
                emb.description = str(wikipedia.summary(message.content[7:]))[:500] + "..." + " \n*Read more here: " + str(page.url) + "*"
                await client.send_message(message.channel, embed=emb)
            except wikipedia.exceptions.DisambiguationError as exception:
                emb = discord.Embed()
                emb.title = "Couldn't find any Wikipedia pages, try these:"
                emb.description = ", ".join(exception.options)
                msg = await client.send_message(message.channel, embed=emb)
                tempMessage = 30
        
        elif message.content.startswith("//define"):
            dictionary=PyDictionary()
            if dictionary.meaning(message.content[9:]) == None:
                error = "Sorry I can't seem to find a definition for that."
                tempMessage = 5
            else:
                emb = discord.Embed()
                emb.title = str(":abc: Definition: " + message.content[9:])
                emb.description = str(dictionary.meaning(message.content[9:]))
                await client.send_message(message.channel, embed=emb)
        
        elif message.content.startswith("//antonym"):
            dictionary=PyDictionary()
            if dictionary.meaning(message.content[9:]) == None:
                error = "Sorry I can't seem to find an antonym for that."
                tempMessage = 5
            else:
                emb = discord.Embed()
                emb.title = str(":ab: Antonym: " + message.content[10:])
                emb.description = ", ".join(dictionary.antonym(message.content[10:]))
                await client.send_message(message.channel, embed=emb)
        
        elif message.content.startswith("//synonym"):
            dictionary=PyDictionary()
            if dictionary.meaning(message.content[9:]) == None:
                error = "Sorry I can't seem to find an synonym for that."
                tempMessage = 5
            else:
                emb = discord.Embed()
                emb.title = str(":abcd: Synonym: " + message.content[10:])
                emb.description = ", ".join(dictionary.synonym(message.content[10:]))
                await client.send_message(message.channel, embed=emb)

        elif message.content.startswith("//french"):
            dictionary=PyDictionary()
            if dictionary.meaning(message.content[9:]) == None:
                error = "Sorry I can't seem to translate that. (one word please)"
                tempMessage = 5
            else:
                emb = discord.Embed()
                emb.title = str(":symbols: Engligh: " + message.content[9:])
                emb.description = "**French:** " + str(dictionary.translate(message.content[9:],'fr'))
                await client.send_message(message.channel, embed=emb)


        elif message.content.startswith("//pepper" or "//peppery"):
            msg = await client.send_file(message.channel, "pepper.png")
            tempMessage = 30

        elif message.content.startswith("//spam"):
            #right click spam channel for id
            arguments = message.content.split()
            conString = ""
            if message.channel.name == "spam": #or message.channel.id == "id"
                try:
                    int(arguments[1])
                except:
                    error = "Invalid format! //spam <amount> <message...>"
                    tempMessage = 5
                    return
                for word in arguments[2:]:
                    conString = conString + " " + word
                if int(arguments[1]) <= 10:
                    for x in range(int(arguments[1])):
                        await client.send_message(message.channel, conString)
                elif int(arguments[1]) > 10:
                    error = "I can't spam that much!"
                    tempMessage = 5
            else:
                error = "You may only use this in the spam text channel."
                tempMessage = 5

        elif message.content.startswith("//morse"):
            decoded = (str(message.content[8:]))
            decoded = decoded.lower()
            msg = await client.send_message(message.channel, "```" + morseCommand.encode(decoded) + "```" + message.author.mention)

        elif message.content.startswith("//demorse"):
            encoded = (str(message.content[10:]) + " ")
            msg = await client.send_message(message.channel, "```" + morseCommand.decode(encoded) + "```" + message.author.mention)

        elif message.content.startswith("//flip" or "//flipr"):
            if message.content.startswith("//flip "):
                unflip = (str(message.content[7:]))[::-1]
            else:
                unflip = (str(message.content[8:]))
            unflip = unflip.lower()
            msg = await client.send_message(message.channel, morseCommand.flip(unflip))

        elif message.content.startswith('//repeat'):
            try:
                if message.content.startswith('//repeat init'):
                    if message.author.top_role.name == 'Admin':
                        global stored
                        stored = []
                        msg = await client.send_message(message.channel, '```Initialized!```' + message.author.mention)
                        tempMessage = 3
                    else:
                        msg = await client.send_message(message.channel, '```Insufficient permissions!```' + message.author.mention)
                        tempMessage = 3
                elif message.content.startswith('//repeat save'):
                    found = False
                    if len(stored) > 0:
                        for mes in range(len(stored)):
                            if stored[mes][0] == message.author.mention:
                                stored[mes][1] = message.content[14:]
                                msg = await client.send_message(message.channel, '```Message recorded!```' + message.author.mention)
                                tempMessage = 3
                                found = True
                        if found == False:
                            stored.append([message.author.mention, message.content[14:]])
                            msg = await client.send_message(message.channel, '```Message recorded!```' + message.author.mention)
                            tempMessage = 3
                            found = True
                    else:
                        stored.append([message.author.mention, message.content[14:]])
                        msg = await client.send_message(message.channel, '```Message recorded!```' + message.author.mention)
                        tempMessage = 3
                        found = True
                elif message.content.startswith('//repeat call'):
                    found = False
                    for mes in range(len(stored)):
                        if stored[mes][0] == message.author.mention:
                            if len(stored[mes][1]) == 0:
                                msg = await client.send_message(message.channel, '``` ```**Message from: **' + message.author.mention)
                            else:
                                msg = await client.send_message(message.channel, '```' + stored[mes][1] + '```**Message from: **' + message.author.mention)
                            found = True
                    if found == False:
                        msg = await client.send_message(message.channel, '```No messages found!```' + message.author.mention)
                        tempMessage = 3
                        found = True
                else:
                    msg = await client.send_message(message.channel, '```Invalid subcommand!```' + message.author.mention)
                    tempMessage = 3
            except:
                msg = await client.send_message(message.channel, '```Not initialized!```' + message.author.mention)
                tempMessage = 3

        elif message.content.startswith("//anon"):
            mes = message.content[7:]
            msg = await client.send_message(message.channel, mes + "\n**~Anonymous :speech_balloon:**")

        elif message.content.startswith("//reverse"):
            mes = str(message.content[:9:-1])
            msg = await client.send_message(message.channel, "```" + mes + "```")

        elif message.content.startswith("//colour list"):
            msg = await client.send_message(message.channel, message.author.mention + " colours: " +", ".join(colours))
            tempMessage = 10

        elif message.content.startswith("//colour"):
            for colour in colours:
                await asyncio.sleep(0.1)
                removeRole = discord.utils.find(lambda d: d.name == "colour-" + colour, message.channel.server.roles) #thanks Khang, lambda master
                await client.remove_roles(message.author, removeRole)
            await asyncio.sleep(0.5)
            userColour = message.content[9:]
            colourRole = discord.utils.find(lambda r: r.name == "colour-" + userColour, message.channel.server.roles)
            await client.add_roles(message.author, colourRole)

        elif message.content.startswith("//hexcolour"):
            hx = str(message.content[12:18])
            hx = hx.upper()
            digs = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"]
            valid = True
            for dig in hx:
                if dig not in digs:
                    valid = False
            while len(hx) < 6:
                hx = "0" + hx
            if valid == False:
                msg = await client.send_message(message.channel, "```Invalid colour!```" + message.author.mention)
                await asyncio.sleep(3)
                await client.delete_message(msg)
            else:
                hxint = int("0x" + hx, 16)
                newrole = discord.utils.get(message.server.roles, name = "#" + hx)
                if newrole not in message.server.roles:
                    await asyncio.sleep(0.2)
                    await client.create_role(server=message.server, name="#" + hx, colour=discord.Colour(hxint), mentionable=False, hoist=False)
                for rol in message.author.roles:
                    if str(rol)[0] == "#":
                        rolefound = 0
                        for mem in message.server.members:
                            if rol in mem.roles:
                                rolefound += 1
                        if rolefound <= 1:
                            await asyncio.sleep(0.2)
                            await client.delete_role(server=message.server, role=rol)
                        await asyncio.sleep(0.2)
                        await client.remove_roles(message.author, rol)
                for rol in message.server.roles:
                    if str(rol) == "#" + hx:
                        await asyncio.sleep(0.2)
                        await client.add_roles(message.author, rol)

        elif message.content.startswith("//notify on"):
            try:
                topic = message.content[12:]
                topicRole = discord.utils.find(lambda r: r.name == "notify-" + topic, message.channel.server.roles)
                await client.add_roles(message.author, topicRole)
                msg = await client.send_message(message.channel, ":bell: " + message.author.mention + ", you have been opted in to receive notifications for " + topic)
                tempMessage = 5
            except:
                error = "Something went wrong."
                tempMessage = 5


        elif message.content.startswith("//notify off"):
            try:
                topic = message.content[13:]
                topicRole = discord.utils.find(lambda r: r.name == "notify-" + topic, message.channel.server.roles)
                await client.remove_roles(message.author, topicRole)
                msg = await client.send_message(message.channel, ":no_bell: " + message.author.mention + ", you have been opted out of receiving receive notifications for " + topic)
                tempMessage = 5
            except:
                error = "Something went wrong."
                tempMessage = 5

        elif message.content.startswith("//notify list"):
            msg = await client.send_message(message.channel, ":bellhop: " + message.author.mention + " //notify <on/off> <channel> - Channel Options: rocket league, minecraft, announcements")
            tempMessage = 10

            #await client.send_message(message.author, "10")
            #await client.send_message(message.channel, "WOW!", tts=True) # tts will read the message
            #await client.change_presence(status=discord.Status.dnd) #fix -> changes status

            #await client.add_roles(message.author, *roles)
            #server = message.author.server
            #member = discord.utils.find(lambda r: r.name == "colour1", server.roles)
            #print(member.id)
            #message.channel.id
            #await client.add_roles(message.author, "colour1")
            #print(member)

        #elif message.content.startswith("//suggest"):

        elif message.content.startswith("//invite"):
            msg = await client.send_message(message.channel, "https://discord.gg/M9hBtqn")
            tempMessage = 15

        elif message.content.startswith("//suggest emoji"):

            adminChannel = client.get_channel("256589191444430848")
            await client.send_message(adminChannel, ":upside_down: Emoji suggestion created by: " + message.author.mention + " - Emoji:" + message.content[15:])
            msg = await client.send_message(message.channel, ":upside_down:" + message.author.mention + "Sent to an admin as an emoji suggestion. Inappropriate suggestions may lead to consequences.")
            tempMessage = 10

        elif message.content.startswith("//suggest splash"):
            adminChannel = client.get_channel("256589191444430848")
            await client.send_message(adminChannel, ":sweat_drops: Splash suggestion created by: " + message.author.mention + " - **Playing**" + message.content[16:])
            msg = await client.send_message(message.channel, ":sweat_drops: " + message.author.mention + ", Sent to an admin as a splash suggestion. Inappropriate suggestions may lead to consequences. Preview: **Playing**" + message.content[16:])
            tempMessage = 10

        elif message.content.startswith("//suggest"):
            adminChannel = client.get_channel("256589191444430848")
            await client.send_message(adminChannel, ":clipboard:  Suggestion created by: " + message.author.mention + " - " + message.content[10:])
            msg = await client.send_message(message.channel, ":clipboard: " + message.author.mention + ", Sent to an admin as an overall suggestion. Inappropriate suggestions may lead to consequences.")
            tempMessage = 10

        elif message.content.startswith("//prime"):
            s = int(message.content[8:])
            if s <= 19999999999997:
                p = int(message.content[8:]) - 1
                l = []
                if p == 1:
                    p -= 1
                if p % 2 == 0.0:
                    p -= 1
                c = 0
                while len(l) <= 1:
                    p += 2
                    d = 0
                    c = 0
                    while d < p ** (1/2) and c <= 1:
                        d += 1
                        if (p / d) % 1 == 0.0:
                            c += 1
                    if c == 1:
                        l.extend([p])
                if l[0] == 1:
                    l[0] = 2
                orig = ""
                final = ""
                s = str(s)
                f = str(l[0])
                for i in range(len(s)):
                    if len(orig) % 4 == 0:
                        orig += "\'"
                    orig += s[-i - 1]
                for i in range(len(f)):
                    if len(final) % 4 == 0:
                        final += "\'"
                    final += f[-i - 1]
                msg = await client.send_message(message.channel, "```" + orig[-1:0:-1] + " -> " + final[-1:0:-1] + "```" + message.author.mention)
            else:
                error = "Your number is too high!"
                tempMessage = 5

        elif message.content.startswith("//rules"):#############################
                error = "Sorry this command is in the works! Type //help instead!"
                tempMessage = 10

        elif message.content.startswith("//remind"):
            if message.author.top_role.name == "Admin":
                remall = message.content[9:]
                remtr = ""
                rem = ""
                spc = False
                for i in range(len(remall)):
                    if remall[i] == " " and spc == False:
                        spc = True
                    if spc == False:
                        remtr = remtr + remall[i]
                    if spc == True:
                        rem = rem + remall[i]
                remtr = int(remtr) - 1
                await asyncio.sleep(remtr)
                await client.send_typing(message.channel)
                msg = await client.send_message(message.channel, "```http\nReminder:" + rem + "```@everyone")
            else:
                error = "You do not have permission to use this command."
                tempMessage = 5
            
        elif message.content.startswith("//timer"):
            tr = int(message.content[8:])
            timermsg = await client.send_message(message.channel, ":alarm_clock: Timer:" + str(tr) + " seconds.")
            count = 5
            while tr >= 1:
                if count == 5:
                    await client.edit_message(timermsg, ":alarm_clock: Timer: " + str(tr) + " seconds.")
                    count = 0
                await asyncio.sleep(1)
                tr -= 1
                count += 1
            await client.delete_message(timermsg)
            await client.send_typing(message.channel)
            msg = await client.send_message(message.channel, "```Time is up!```" + message.author.mention)
            tempMessage = 5

        elif message.content.startswith("//delete"):
            try:
                if int(message.content[9:]) > 10:
                    msg = await client.send_message(message.channel, ":wastebasket: Slow down there!")
                    await asyncio.sleep(5)
                    await client.delete_message(msg)
                elif message.author.top_role.name == "Admin":
                    await client.purge_from(message.channel, limit=int(message.content[9:]))
                    msg = await client.send_message(message.channel, ":wastebasket: Deleted " + message.content[9:] + " message(s).")
                    await asyncio.sleep(5)
                    await client.delete_message(msg)
                else:
                    error = "You do not have permission to use this command."
                    tempMessage = 5
            except:
                error = "Not a valid number."
                tempMessage = 5
                
        elif message.content.startswith("//room"):
            if message.content.startswith("//room create"):
                pchname = "Private " + str(message.author)
                pch = discord.utils.get(message.server.channels, name = pchname, type = discord.ChannelType.voice)
                if pch not in message.server.channels:
                    pcheveryoneperms = discord.PermissionOverwrite(connect=False)
                    pchroleperms = discord.PermissionOverwrite(connect=True)
                    pchrole = await client.create_role(server=message.server,name=pchname,mentionable=True,hoist=False)
                    await client.add_roles(message.author, pchrole)
                    await client.create_channel(message.server, pchname, (message.server.default_role, pcheveryoneperms), (pchrole, pchroleperms), type=discord.ChannelType.voice)
                    msg = "Private channel created!\n" + str(message.author.mention)
                    tempMessage = 3
                else:
                    error = "You already have a private channel!\n" + str(message.author.mention)
                    tempMessage = 3
            elif message.content.startswith("//room delete"):
                pchname = "Private " + str(message.author)
                pch = discord.utils.get(message.server.channels, name = pchname, type = discord.ChannelType.voice)
                pchrole = discord.utils.get(message.server.roles, name = pchname)
                if pch in message.server.channels:
                    await client.delete_channel(pch)
                    await client.delete_role(message.server, pchrole)
                    msg = "Private channel deleted!\n" + str(message.author.mention)
                    tempMessage = 3
                else:
                    error = "No private channel exists to be deleted!\n" + str(message.author.mention)
                    tempMessage = 3
            elif message.content.startswith("//room invite all"):
                pchname = "Private " + str(message.author)
                pchrole = discord.utils.get(message.server.roles, name = pchname)
                msg = "Inviting all members to " + pchname + "..."
                for mem in message.server.members:
                    if (pchrole not in mem.roles) and (mem != message.author):
                        await client.add_roles(mem, pchrole)
                tempMessage = 0
                msg = "Invited all members to " + pchname + "!"
                tempMessage = 5
            elif message.content.startswith("//room uninvite all"):
                pchname = "Private " + str(message.author)
                pchrole = discord.utils.get(message.server.roles, name = pchname)
                msg = "Uninviting all members to " + pchname + "..."
                for mem in message.server.members:
                    if (pchrole in mem.roles) and (mem != message.author):
                        await client.remove_roles(mem, pchrole)
                tempMessage = 0
                msg = "Unnvited all members to " + pchname + "!"
                tempMessage = 5
            elif message.content.startswith("//room invite"):
                await client.send_typing(message.channel)
                pchname = "Private " + str(message.author)
                pchrole = discord.utils.get(message.server.roles, name = pchname)
                if len(message.mentions) == 0:
                    error = "Cannot invite 0 people!\n" + message.author.mention
                    tempMessage = 3
                for newmember in message.mentions:
                    if (newmember in message.server.members) and (pchrole not in newmember.roles):
                        await client.add_roles(newmember, pchrole)
                        msg = "You have been invited to " + pchname + "!\n" + newmember.mention
                        tempMessage = 7
                    elif (newmember in message.server.members) and (pchrole in newmember.roles):
                        error = str(newmember) + " is already invited to " + pchname + "!"
                        tempMessage = 5
                    else:
                        error = "Member not found!\n" + message.author.mention
                        tempMessage = 3
            elif message.content.startswith("//room uninvite"):
                pchname = "Private " + str(message.author)
                pch = discord.utils.get(message.server.channels, name = pchname, type = discord.ChannelType.voice)
                pchrole = discord.utils.get(message.server.roles, name = pchname)
                if len(message.mentions) == 0:
                    error = "Cannot uninvite 0 people!\n" + message.author.mention
                    tempMessage = 3
                for newmember in message.mentions:
                    if (newmember in message.server.members) and (pchrole in newmember.roles):
                        if newmember == message.author:
                            await client.send_typing(message.channel)
                            error = "Cannot uninvite yourself!\n" + message.author.mention
                            tempMessage = 3
                        else:
                            await client.remove_roles(newmember, pchrole)
                            msg = "You have been uninvited to " + pchname + "!\n" + newmember.mention
                            tempMessage = 7
                            if newmember.voice_channel.id == pch.id:
                                await client.move_member(newmember, message.server.afk_channel)
            else:
                error = "Invalid subcommand!\n" + message.author.mention
                tempMessage = 3

        elif message.content.startswith("//numbergame"):
            global number
            number = -1
            beforetr = 10
            tr = 5
            timermsg = await client.send_message(message.channel, ":1234: @here Number game starting in " + str(beforetr) + " seconds.")
            await asyncio.sleep(beforetr - tr)
            while tr >= 1:
                await client.edit_message(timermsg, ":1234: @here Number game starting in " + str(tr) + " seconds.")
                await asyncio.sleep(1)
                tr -= 1
            await client.delete_message(timermsg)
            number = random.randint(1, 100)
            ingame = message.author
            msg = await client.send_message(message.channel, ":1234: Guess the number! (between 1 and 100)")
            count = 60
            while count >= 0 and number != -1:
                count -= 1
                await asyncio.sleep(1)
                #print(count >= 0 and number != -1, count, number)
            if number != -1:
                await client.delete_message(msg)
                msg = await client.send_message(message.channel, ":1234: Times up!")
                number = -1
                await asyncio.sleep(5)
                await client.delete_message(msg)            
                
        elif message.content.startswith("//"):
            error = "Sorry the \"" + message.content + "\" command does not exist! Use //help for more information."
            tempMessage = 5
            #roles = message.author.roles[1]
            #print(roles.name)
            


#-----------------------------------------------------------------------------------------------------------------------------------------

    if error != "":
        msg = await client.send_message(message.channel, ":no_entry_sign: " + message.author.mention + ", " + error)
        
    if tempMessage != 0:
        await asyncio.sleep(tempMessage)
        await client.delete_message(msg)

#-----------------------------------------------------------------------------------------------------------------------------------------

    try: #number game cont
        if number >= 1:
            if int(message.content) < number:
                await client.send_typing(message.channel)
                await client.delete_message(message)
                msg = await client.send_message(message.channel, "The number is larger than " + message.content)
                await asyncio.sleep(5)
                await client.delete_message(msg)
            elif int(message.content) > number:
                await client.send_typing(message.channel)
                await client.delete_message(message)
                msg = await client.send_message(message.channel, "The number is smaller than " + message.content)
                await asyncio.sleep(5)
                await client.delete_message(msg)
            elif int(message.content) == number:
                await client.send_typing(message.channel)
                await client.delete_message(message)
                await client.send_message(message.channel, "Congrats " + str(number) + " was the number " + message.author.mention)
                number = -1

    except:
        return
Ejemplo n.º 42
0
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)
Ejemplo n.º 43
0
from PyDictionary import PyDictionary

dictionary=PyDictionary()
features="html.parser"

print (dictionary.meaning(""))

print (dictionary.synonym(""))

print (dictionary.antonym(""))
Ejemplo n.º 44
0
from PyDictionary import PyDictionary

dictionary = PyDictionary()

word = raw_input("Enter a word")

print(dictionary.synonym(word))

Ejemplo n.º 45
0
"""

from PyDictionary import PyDictionary
dictionary=PyDictionary()
in1=input('letter')
in2=input('sentence')
in2=in2.split(' ')
final=[]
final1=[]
abc=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
for pie in abc:
    final=[]
    for elem in in2:
        var=elem
        try:
            for leme in dictionary.synonym(elem):
                if list(leme)[0]==pie:
                    var=leme
        except TypeError:
            var=elem
        
        final.append(var)
    final1.append(' '.join(final))
nextlist=[]
nextlist1=[]
counts=[]
high=[0,0]
for elm in final1:
    nextlist=elm.split(' ')
    nextlist1=[]
    counts=[]