Ejemplo n.º 1
0
def dict_search(x):
    x = x.lower()
    if x in data:
        defin = data[x]
        t = 0
        
        for i in defin:
            t = t + 1
            print(str(t) + ". " + i)
        print("\n")

    elif len(gcm(x, data.keys())) > 0:
        
        cls_match = gcm(x, data.keys())
        first_term = cls_match[0]
        rec_srch = input("Did you mean {} instead? (Y/N) ".format(first_term))

        if rec_srch == "Y" or rec_srch == "y":
            print("\n" + first_term.title() + ":")
            correct_search(first_term)
        elif:
            print("The word you searched does not exist")
        else:
            print("Entry not recognized")
    else:
        print("WORD NOT FOUND")
Ejemplo n.º 2
0
def find_close_match(w):
    if len(gcm(w, data.keys(), cutoff=0.8)) > 0:
        word = gcm(w, data.keys(), cutoff=0.8)[0]
        if str(input(('Did you mean "%s" instead? :' % word))).lower() in l:
            find_meaning(word)
    else:
        raise Exception('No matching word found')
Ejemplo n.º 3
0
def extract_skills(info, threshold=0.9):
    words, unigrams, bigrams, trigrams = clean_info(info)
    results = []
    for skill in SKILLS:
        s = skill
        if '(' in s:
            abb = s[s.find("(") + 1:s.find(")")]
            if abb in words:
                results.append(skill)
                continue
            s = re.sub(r"[\(].*?[\)]", "", s)
        s = s.lower()
        s2 = s.split()
        if len(s2) > 1:
            if s in info.lower():
                results.append(skill)
                continue
        if len(s2) == 1:
            if len(gcm(s, unigrams, cutoff=threshold)) > 0:
                results.append(skill)
        elif len(s2) == 2:
            if len(gcm(s, bigrams, cutoff=threshold)) > 0:
                results.append(skill)
        elif len(s2) == 3:
            if len(gcm(s, trigrams, cutoff=threshold)) > 0:
                results.append(skill)
        else:
            if len(gcm(s, trigrams, cutoff=threshold)) > 0:
                results.append(skill)
    results = [SKILL_DICT[s] if s in SKILL_DICT.keys() else s for s in results]
    return list(set(results))
Ejemplo n.º 4
0
def return_definition(word):

    word = word.lower()
    error_tolerance = 0.7
    if word in data:
        return data[word]
    elif word.title() in data:
        return data[word.title()]
    elif word.upper() in data:
        return data[word.upper()]
    elif len(gcm(word, data.keys(), cutoff=error_tolerance)) != 0:
        reply = input("Did u mean {0}?Enter the index or enter N.".format(
            gcm(word, data.keys(), cutoff=error_tolerance)))
        if reply == '1':
            return data[gcm(word, data.keys(), cutoff=error_tolerance)[0]]
        elif reply == "2":
            return data[gcm(word, data.keys(), cutoff=error_tolerance)[1]]
        elif reply == "3":
            return data[gcm(word, data.keys(), cutoff=error_tolerance)[2]]
        elif reply == 'N':
            return "The word doesn't exist. PLease check again."
        else:
            return "Didn't understand your entry."
    else:
        return ["The word doesn't exist. Please check again."]
Ejemplo n.º 5
0
def translate(word):
    if (word in data):
        return data[word]
    elif len(gcm(word, data.keys(), cutoff=0.75)) > 0:
        yn = input("Did you mean %s instead?Enter Y if yes, or N if no" %
                   gcm(word, data.keys())[0])
        if (yn.lower() == "y"):
            return data[gcm(word, data.keys())[0]]
        else:
            return "Word doesnt exist. Please double check it"
    else:
        return "Word doesnt exist. Please double check it"
Ejemplo n.º 6
0
async def w(ctx):
    msg = ctx.message.content
    if len(msg) < 4:
        return
    channel_ids = {
        '342419901870505984': 'novato',
        '495682875732131840': 'so_novato',
        '424011906177564691': 'marinwood_tl',
        '342837391922429952': 'sr',
        '342837467713634314': 'rv',
        '436032119718805505': 'central',
        '342837520171532288': 'southern',
        '246877047488512000': 'all'
    }
    channel_id = str(ctx.message.channel.id)
    if channel_id not in channel_ids:
        channel_name = 'all'
    else:
        channel_name = channel_ids[channel_id]
    gym_name = msg[3:]
    with open(f'gyms/{channel_name}.json', 'r') as f:
        gyms = json.load(f)
    gcm_result = gcm(gym_name, gyms)
    if gcm_result:
        # add cutoff=0.7 possibly
        gym_name = gcm_result[0]
    else:
        alias_list = {}
        for gym in gyms:
            for alias in gyms[gym]['aliases']:
                alias_list[alias] = gym
        gcm_result = gcm(gym_name, alias_list)
        if gcm_result:
            gym_name = alias_list[gcm_result[0]]
        else:
            await ctx.send('Gym not found')
            return

    lat = gyms[gym_name]['lat']
    lng = gyms[gym_name]['lng']
    url = f'http://maps.google.com/maps?q={lat},{lng}'
    address = gmaps.reverse_geocode(f'{lat},{lng}')[0]['formatted_address']
    embed = discord.Embed(title=gym_name,
                          url=url,
                          colour=discord.Colour(random.randint(0, 16777215)),
                          description=f'{address}\n\n{url}')
    if 'img' in gyms[gym_name]:
        embed.set_thumbnail(url=gyms[gym_name]['img'])
    embed.set_image(url=f'https://maps.googleapis.com/maps/api/staticmap'
                    f'?center{lat},{lng}&markers=color:red%7C'
                    f'{lat},{lng}&size=250x125&zoom=15&key={gkey}')
    await ctx.send(embed=embed)
Ejemplo n.º 7
0
def translate(w):
    w = w.lower()
    if w in data:
        return data[w]
    elif len(gcm(w, data.keys())) > 0:
        yn = input("Did you mean  %s instead? Enter Y if yes or N if No: " %
                   gcm(w, data.keys())[0])
        if (yn.lower() == 'y'):
            return data[gcm(w, data.keys())[0]]
        else:
            return "The word doesnt exist. Please Double check it"
    else:
        return "The word doesnt exist. Please Double check it"
Ejemplo n.º 8
0
def find_definition(word):
    word = word.lower()
    if word in data:
        return data[word]
    elif len(gcm(word, data, n=1)) > 0:
        suggestion = gcm(word, data, n=1)
        response = input("Did you mean %s? (Y/N) " % suggestion[0])
        if response.lower() == "y":
            return data[suggestion[0]]
        elif response.lower() == "n":
            return "I don't know what word you are looking for. Please try again."
    else:
        return "The word doesn't exist. Please double check it."
Ejemplo n.º 9
0
def translate(word):
    if word.lower() in data:
        return '\n'.join(data[word.lower()])
    elif word.capitalize() in data:
        return '\n'.join(data[word.capitalize()])
    elif word.upper() in data:
        return '\n'.join(data[word.upper()])
    elif gcm(word, list(data.keys()), n=1, cutoff=0.6):
        c_word = ''.join(gcm(word, list(data.keys()), n=1, cutoff=0.6))
        answer = input("Didn't find word, did you mean '{}' instead '{}'?\n".format(c_word, word)\
                       +"Y/N: ")
        return '\n'.join(data[c_word]) if answer.upper() == 'Y' else main()
    else:
        return "The word does not exist!"
Ejemplo n.º 10
0
def translate(w):
    w = w.lower()
    if w in data:
        return data[w]
    elif len(gcm(w, data.keys())) > 0:
        yn = input("Did you mean %s instead? Enter Y if yes or N if no: \n" %
                   gcm(w, data.keys())[0])
        if yn == "Y":
            return data[gcm(w, data.keys())[0]]
        elif yn == "N":
            return "The word doesn\'t exists. Please double check the entered word."
        else:
            return "We did not understand you query"
    else:
        return "The word doesn\'t exists. Please double check the entered word."
Ejemplo n.º 11
0
def define_word(word):
	word = word.lower()
	if word in data.keys():		#If searched word is a key in dict, return it
		return data[word]
	elif len(gcm(word, data.keys(), cutoff = 0.8)) > 0:	#If word does not exist in keys, but is similar enough to words that do
		mist = input("Did you mean %s instead of %s ? Enter Y for yes, and N for no:\n" %(gcm(word, data.keys(), cutoff = 0.8)[0], word)) 
		if mist == 'Y':
			return data[gcm(word, data.keys(), cutoff = 0.8)[0]]	#Return first element of the list of similar words returned by function get_close_matches
		elif mist == 'N':
			return "Sorry, the word does not exist"
		else: 
			return "Sorry, invalid input"
		
	else:
		print("Sorry, invalid input")
Ejemplo n.º 12
0
def meaning(word):
    word = word.lower()

    if(word in data):
        return data[word]
    elif(len(gcm(word, data.keys())) > 0):
        option = input("Did you mean %s? Enter Y if yes, N if no: " %gcm(word, data.keys())[0])
        if(option == "Y"):
            return data[gcm(word, data.keys())[0]]
        elif(option == "N"):
            return "The word dosen't exist. Please check again."
        else:
            return "We did not understand your query"
    else:
        return "The word dosen't exist. Please check again."
Ejemplo n.º 13
0
def searchDict(keyword):
    if keyword in data:
        return data[keyword]
    elif len(gcm(keyword, data.keys())) > 0:
        suggestion = gcm(keyword, data.keys())[0]
        response = input(
            "Word not found in the dictionary. Did you mean {0}? Y/N: ".format(
                suggestion))
        if (response.lower() == "y"):
            return searchDict(suggestion)
        else:
            print("Sorry try again.")
    else:
        print(
            "The word you're looking for doesn't exist in the dictionary. Please try again."
        )
Ejemplo n.º 14
0
def translate(dict_keyword):
    dict_keyword = dict_keyword.lower()
    vocab_content = open_json_file('data.json')
    possibilities = gcm(dict_keyword, vocab_content.keys(), 6, 0.7)

    if dict_keyword in vocab_content:
        beauty_out(vocab_content[dict_keyword], '  def.')
    elif dict_keyword.title() in vocab_content:
        beauty_out(vocab_content[dict_keyword.title()], '  def.')
    elif dict_keyword.upper() in vocab_content:
        beauty_out(vocab_content[dict_keyword.upper()], '  def.')
    elif len(possibilities) > 0:
        while 0 < 1:
            try:
                print("\nYour word has not been found. Did you mean...")
                beauty_out(possibilities, '   ')
                corrected_ans = input(
                    "\nDid you mean any of these? Enter number {}-{} to choose "
                    "a proper word: ".format(1, len(possibilities)))
            except (SyntaxError, NameError):
                print('Only number input is allowed in submenu.')
            else:
                try:
                    dict_keyword = possibilities[corrected_ans - 1]
                except IndexError:
                    print("Number out of range passed. Enter again: ")
                else:
                    print("\nChosen word: {}".format(dict_keyword.upper()))
                    beauty_out(vocab_content[dict_keyword], '  def.')
                    break
    else:
        print "The word doesn't exist. Please, double check it."
Ejemplo n.º 15
0
def returnDefinition(data, key):
    key = key.lower()
    if key in data:
        return data[key]
    elif key.title() in data:
        return data[key.title()]
    elif key.upper() in data:
        return data[key.upper()]
    elif len(gcm(key, data.keys()))>0:
        answer = input("Did you mean %s instead? [Y/n]" % gcm(key, data.keys())[0])
        if answer == 'Y':
            return data[gcm(key, data.keys())[0]]
        else:
            return 'Unable to find the word'
    else:
        return 'Unable to search for the word'
Ejemplo n.º 16
0
def get_definition(word):
    word = word.lower()
    if word in data:
        return data[word]
    elif len(gcm(word, data.keys())) > 0:
        yorn = input('Did you mean %s instead? Enter y if yes and n if no: ' %
                     gcm(word, data.keys())[0])
        yorn = yorn.lower()
        if yorn == 'y':
            return data[gcm(word, data.keys())[0]]
        elif yorn == 'n':
            return 'We could not find this word'
        else:
            return 'We could not understand your entry'
    else:
        return 'We could not find this word'
Ejemplo n.º 17
0
def search_dict(word):
    if word.title() in source:
        return source[word.title()]
    elif word in source:
        return source[word]
    elif word.upper() in source:
        return source[word.upper()]
    elif gcm(word, source.keys(), cutoff=0.8) is not []:
        check = input(
            f"Did you mean {gcm(word, source.keys()) [0]}? Y - yes | N - no: ")
        if check.lower() == "y":
            return source[gcm(word, source.keys())[0]]
        else:
            return "Sorry, that word is not in dictionary. Please check you typing"
    else:
        return "Sorry, that word is not in dictionary. Please check you typing"
Ejemplo n.º 18
0
def get_value_by_key(key):

    query_keys = [key, key.title(), key.upper()]

    for query in query_keys:
        data = make_query(query)
        if data:
            return data

    expressions = make_query('expression')
    analog_key = gcm(key, expressions, n=1)
    if len(analog_key) > 0:
        yn = input(
            "the word is not in dictionary. did u mean %s? Enter Y or N: " %
            analog_key[0].lower())

        if yn == 'y':
            data = make_query(analog_key[0])
            return data

        elif yn == 'n':
            return "Sorry(((. Try another word."

        else:
            return "we didn`t understent your input."

    else:
        return "the word is not in dictionary."
Ejemplo n.º 19
0
def translate(query):
    query = query.lower()
    if (query in data.keys()):
        a = data[query]
        for i in a:
            print(i)
    elif(gcm(query,data_key,3)):
        query = gcm(query,data_key,3)[0]
        ans = input("Did you mean  - '%s'? " %query)
        if (ans == 'yes'):
            translate(query)
        elif (ans == "no"):
            print("Sorry, No Result")
        else:
            print("Sorry, Did not get your entry.")
    else:
        print("Sorry, No Result")
Ejemplo n.º 20
0
def translate(word):
    word = word.lower()

    if word in data:
        return data[word]
    elif len(gcm(word, data.keys())) > 0:
        yn = input('Did you mean {s} instead? (Y/N) '.format(
            s=gcm(word, data.keys())[0]))
        if yn.lower() == 'y':
            return data[gcm(word, data.keys())[0]]
        elif yn.lower() == 'n':
            return 'The word does not exist'
        else:
            return 'We didn\'t understand your response'

    else:
        return 'The word does not exist.'
Ejemplo n.º 21
0
def dictionary(w):
    # converts the word to lowercase
    w = w.lower()

    # Checks if the i/p data is present in the dictionary
    if w in data:
        return (data[w])

    # Checks if the word is similar to another word in the dictionary if the input is incorrect
    elif len(gcm(w, data.keys())) > 0:
        return ("Did you mean %s ?" % gcm(w, data.keys(), cutoff=0.6)[0])
        '''
            gcm is a function that compares the i/p word to the keys of the dictionary 
            and how similar they are and gives a list of the similar keys as input
        '''
    else:
        return ("word doesn't exist")
Ejemplo n.º 22
0
def defi(w):
    w = w.lower()
    if w in dat:
        return [w, dat[w]]
    elif len(gcm(w, dat.keys(), n=3, cutoff=0.75)) > 0:
        i = 0
        l = gcm(w, dat.keys(), n=3, cutoff=0.75)
        print("Enter Y(y) if yes or N(n) if no.")
        while i < len(l):
            yn = input("Did you mean '%s' instead?: " % l[i])
            if yn == "Y" or yn == "y":
                return [l[i], dat[l[i]]]
            elif yn == "N" or yn == "n":
                i += 1
        return Back.RED + Fore.WHITE + w + Style.RESET_ALL + " ain't in my dictionary."
    else:
        return "Is " + Back.YELLOW + Fore.WHITE + w + Style.RESET_ALL + " a real word? Please double check it."
Ejemplo n.º 23
0
def find_meaning(word):
    if word in data:
        return (data[word])
    elif word.title() in data:
        return (data[word.title()])
    elif len(gcm(word, data.keys())) > 0:
        #get an input from user asking if they meant a closest match from the file we have
        print("word you entered not found, try any from %s instead.: " %
              gcm(word, data.keys(), cutoff=0.8))
        word = input("your word: ")
        if word in data:
            #get_close_matches(word, possibilities, n=3, cutoff=0.6) is default
            return (data[word])
        else:
            print('Word not found')
            return
    else:
        return ("Word not found")
Ejemplo n.º 24
0
def getMean(inp):
    if inp in data:
        return data[inp]
    elif inp.upper() in data:
        return data[inp.upper()]
    elif inp.title() in data:
        return data[inp.title()]
    elif len(gcm(inp, data.keys())) > 0:
        print('did you mean %s instead' % gcm(inp, data.keys())[0])
        decide = input('Press Y for yes or N for no: ')
        if decide.lower() == 'y':
            return data[gcm(inp, data.keys())[0]]
        elif decide.lower() == 'n':
            print('can\'t find the meaning of this word')
        else:
            print('invalid input, enter Y or N')
    else:
        print('can\'t find the meaning of this word')
Ejemplo n.º 25
0
def retrieve(key):
    try:
        if key in data.keys():
            for i in data.get(key):
                print(i)
        elif len(gcm(key, data.keys())) > 0:
            yn = input("Did you mean %s instead? Enter Y is yes or N if no: " %
                       gcm(key, data.keys())[0])
            if yn == "Y" or yn == "y":
                print(data.get(gcm(key, data.keys())[0]))
            elif yn == "n" or yn == "N":
                print("Word does not exist")
            else:
                print("I didn't understand your entry")
        else:
            print("Object does not exist")
    except:
        print("Type error enter a word")
def pmit(phrase, text, min_word_size=3):
    if not (isinstance(phrase, str) and isinstance(text, str)
            and isinstance(min_word_size, int)):
        print("One of the arguments is not valid")
        end = input("")
        return
    non_relevant_char = [
        ",", ".", ":", ";", "?", "/", "'", '"', "!", "<", ">", "@", "#", "$",
        "%", "^", "&", "*", "(", ")", "_", "=", "+", "~", "`"
    ]
    phrase = phrase.split()
    text = text.split()
    for word in phrase:
        if len(word) <= min_word_size - 1:
            phrase.remove(word)
    for word in text:
        if len(word) <= min_word_size - 1:
            text.remove(word)
    phrase = " ".join(phrase)
    text = " ".join(text)
    for character in non_relevant_char:
        text.replace(character, " ")
        phrase.replace(character, " ")
    while text.find("  ") != -1:
        text.replace("  ", " ")
    while phrase.find("  ") != -1:
        phrase.replace("  ", " ")
    phrase = phrase.split()
    if text.find("\n") != -1:
        paragraphs = [text]
    else:
        paragraphs = text.splitlines()
    highest_match_ratio = [0]
    for paragraph in paragraphs:
        paragraph = paragraph.split()
        matches = []
        for pword in phrase:
            close_matches = gcm(pword, paragraph)
            for index in range(0, len(paragraph) - 1):
                if (paragraph[index]
                        in close_matches) and (not index in matches):
                    matches.append(index)
        for match in matches:
            if match - int(len(phrase) / 2) < 0:
                begin = 0
            else:
                begin = match - int(len(phrase) / 2)
            if match + int(len(phrase) / 2) + len(phrase) > len(paragraph) - 1:
                end = len(paragraph) - 1
            else:
                end = match + int(len(phrase) / 2) + len(phrase)
            match_ratio = sm(None, " ".join(phrase),
                             " ".join(paragraph[begin:end])).ratio()
            if match_ratio > highest_match_ratio[0]:
                highest_match_ratio[0] = match_ratio
    result = highest_match_ratio[0]**(1 / len(phrase))
    return result
Ejemplo n.º 27
0
def translate(word):
    word= word.lower()
    if word in data:
        return data[word]
    elif word.title() in data:
        return data[word.title()]
    elif word.upper() in data:
        return data[word.upper()]
    elif len(gcm(word,data.keys()))>0:
        print("Are you looking for %s?"%gcm(word,data.keys())[0])
        decide = input("press y for yes and n for no: ")
        if decide=="y":
            return data[gcm(word,data.keys())[0]]
        elif decide=="n":
            print("The word doesn't exist")
        else:
            print("keyboard hai toh kuch bhi likhoge jitna poocha hai utna type karo")
    else:
        print("The word doesn't exist")
Ejemplo n.º 28
0
def translate(s: str) -> str or list:
    s = s.lower()
    if s in DATA.keys():
        return DATA[s]
    elif len(gcm(s, DATA.keys())) > 0:
        closest_match = gcm(s, DATA.keys())[0]
        yn = input("Did you mean '{}' instead? \n Y/N: ".format(
            closest_match)).upper()
        if yn == "Y":
            return DATA[closest_match]
        elif yn == "N":
            return "The search for '{}' yielded no results. \nPlease double-check your search input.".format(
                s)
        else:
            return "Error: Invalid input."
    else:
        print(
            "The search for '{}' yielded no results. \nPlease double-check your search input."
            .format(s))
Ejemplo n.º 29
0
def translate(word):
    words = (data.keys())
    # print(words)
    for el in words:
        if word.lower() == el:
            return normalize_strs(data[word.lower()])
        elif word.capitalize() == el:
            return normalize_strs(data[word.capitalize()])
        elif word.upper() == el:
            return normalize_strs(data[word.upper()])
    if gcm(word, words, n=1, cutoff=0.6):
        c_word = ''.join(gcm(word, list(data.keys()), n=1, cutoff=0.6))
        answer = input("Didn't find word, did you mean '{}' instead '{}'?\n"\
                .format(c_word.encode('ascii', errors='replace').decode('ascii'), word)\
                +"Y/N: ")
        return normalize_strs(
            data[c_word]) if answer.upper() == 'Y' else main()
    else:
        return "The word does not exist!"
def definition(term):
    term = term.lower()
    if term in data.keys():
        return data[term]
    elif term.title() in data.keys():
        return data[term.title()]
    elif term.upper() in data.keys():
        return data[term.upper()]
    elif len(gcm(term, data.keys())) > 0:
        print("Did you mean '%s'?" % gcm(term, data.keys())[0])
        decision = input("Y or N: ")
        if decision.lower() == "y":
            return data[gcm(term, data.keys())[0]]
        elif decision.lower() == "n":
            return "That word doesn't exist, please check it."
        else:
            return "I'm not sure I understand your query, please try again."
    else:
        return "That word doesn't exist, please check it."
Ejemplo n.º 31
0
    def get_names(cls, student_name, mod_name, filepath):
        """Gets the function names the student used"""

        sys.path[0] = filepath
        globals()["Student"] = __import__(mod_name, globals(), locals())
        cls.names = [globals()["Student"].__dict__.get(var).__name__
                      for var in dir(globals()["Student"])
                      if (isinstance(globals()["Student"].__dict__.get(var),
                                     types.FunctionType) or
                          isinstance(globals()["Student"].__dict__.get(var),
                                     types.ClassType))]

        for name in cls.good_functions:
            match = gcm(name, cls.names)
            if match:
                cls.student_functions[name] = match[0]
            else:
                cls.student_functions[name] = name
Ejemplo n.º 32
0
malay_vocab = Counter(chain(*[word_tokenize(i) for i in malay]))
for i in list(malay_vocab):
    if malay_vocab[i] < 5:
        del malay_vocab[i]

indo_vocab = Counter(chain(*[word_tokenize(i) for i in indo]))
for i in list(indo_vocab):
    if indo_vocab[i] < 5:
        del indo_vocab[i]

for i in indo_vocab:
    if not i.isalpha or [j for j in i if j in string.punctuation]:
        continue
    try:
        int(i)
        continue
    except:
        pass
    
    matches = gcm(i, malay_vocab)
    if not matches:
        continue
    
    if i == matches[0]:
        #print i, matches[0]
        pass
    else:
        if levenshtein(i.lower(),matches[0].lower()) == 1 and \
        len(i) == len(matches[0]):
            print i, matches[0]