def find_rhymes(self, word_bag=None, num_rhymes=10):
        """

        Accepts list of words or word as parameter, returns dictionary of words and rhymes.

        """

        word_bag = self.cached_words if word_bag is None else word_bag

        if isinstance(word_bag, list):

            for word in word_bag:

                rhymes = pronouncing.rhymes(word)

                if len(rhymes) > num_rhymes:

                    self.rhyme_dict[word] = [
                        random.choice(rhymes) for _ in range(num_rhymes)
                    ]

                else:

                    print('Max rhyme capacity reached.')

                    self.rhyme_dict[word] = rhymes

        else:

            self.rhyme_dict[word_bag] = pronouncing.rhymes(
                word_bag)[:num_rhymes]

        return self.rhyme_dict
Example #2
0
def do_rhymes(f_rhyme, s_rhyme):
    # pronouncing.rhymes(first_rhyme) returns a list of words that rhyme with first_rhyme
    print("* Printing words that rhyme with", f_rhyme, "*")
    print()
    rhyme_list_1 = pronouncing.rhymes(f_rhyme)
    print(rhyme_list_1)
    print()
    print()
    print("* Printing words that rhyme with", s_rhyme, "*")
    print()
    rhyme_list_2 = pronouncing.rhymes(s_rhyme)
    print(rhyme_list_2)

    # Picking a random position in rhyme_list
    # Which will rhyme with first_rhyme
    rhyme_list_len_1 = len(rhyme_list_1)
    rhyme_list_len_2 = len(rhyme_list_2)

    for x in range(1):
        rand_rhyme_1 = random.randint(1, rhyme_list_len_1 - 1)
        rand_rhyme_2 = random.randint(1, rhyme_list_len_2 - 1)

    first_rhymer = rhyme_list_1[rand_rhyme_1]
    second_rhymer = rhyme_list_2[rand_rhyme_2]

    print()
    print("* Selected rhymers *")
    print()
    print("1", first_rhymer)
    print("2", second_rhymer)
Example #3
0
def phoneticEndRhymeComparison(lines):

    output = [pronouncing.rhymes(lines[0]), pronouncing.rhymes(lines[1])]

    test_list1 = output[0]
    test_list2 = output[1]

    test_list1 = [str(r) for r in test_list1]
    test_list2 = [str(r) for r in test_list2]

    print('Attempting to add ' + lines[0] + ' to array')
    print(test_list1)

    test_list1 = test_list1.extend(lines[1])
    print(test_list1)

    # print test_list1

    # printing lists
    print("The first list is : " + str(test_list1))
    print("The second list is : " + str(test_list2))

    # sorting both the lists
    test_list1.sort()
    test_list2.sort()

    # using == to check if
    # lists are equal
    if test_list1 == test_list2:
        print("The lists are identical")
    else:
        print("The lists are not identical")
Example #4
0
def remix(lyric):
    t = TweetTokenizer()
    d = TreebankWordDetokenizer()

    words = t.tokenize(lyric)
    r1 = random.randint(0, len(words) - 1)
    # filter out punctuation, stop words, and words with no rhymes
    while words[r1] in string.punctuation or isStopWord(words[r1]) or len(
            pronouncing.rhymes(words[r1])) == 0:
        if len(words) == 1: return lyric
        r1 = random.randint(0, len(words) - 1)

    # this is the word to be replaced
    word = words[r1]
    syl = countSyllables(word)

    # find rhymes with same number of syllables
    rhymes = pronouncing.rhymes(word)
    r2 = random.randint(0, len(rhymes) - 1)
    count = 1
    while (count <= len(rhymes)
           and syl != countSyllables(rhymes[r2])) or isStopWord(rhymes[r2]):
        r2 = random.randint(0, len(rhymes) - 1)
        count += 1
    words[r1] = rhymes[r2]

    return d.detokenize(words)
def get_best_rhyme(first, second):

    f_rhymes = prn.rhymes(first)
    scores_f = get_similarities(second, f_rhymes)
    s_rhymes = prn.rhymes(second)
    scores_s = get_similarities(first, s_rhymes)

    f_active = len(scores_f) > 0 and len(scores_s) == 0
    both_active = len(scores_f) > 0 and len(scores_s) > 0
    s_active = len(scores_s) > 0 and len(scores_f) == 0
    if s_active:
        best_candidate_s = max(scores_s, key=lambda x: x[0])
    if f_active:
        best_candidate_f = max(scores_f, key=lambda x: x[0])
    if both_active:
        best_candidate_s = max(scores_s, key=lambda x: x[0])
        best_candidate_f = max(scores_f, key=lambda x: x[0])

    if f_active or (both_active and best_candidate_f[0] > best_candidate_s[0]):
        return first, best_candidate_f[1]
    elif s_active or (both_active
                      and best_candidate_f[0] <= best_candidate_s[0]):
        return best_candidate_s[1], second
    else:
        return first, second
Example #6
0
    def render(self):
        if self.cf['hose']:
            self.hose = re.compile(self.cf['hose'])
        else:
            self.hose = None
        participles = self.syllfilt(pronouncing.search("IH0 NG$"), 2)
        nouns = self.syllfilt(pronouncing.rhymes('now'), 1)

        rhymes = []
        p1 = None
        p3 = None
        while not rhymes:
            ps = random.sample(participles, 2)
            rhymes = self.syllfilt(pronouncing.rhymes(ps[0]), 2)

        p1 = ps[0]
        p2 = random.choice(rhymes)
        p3 = ps[1]

        noun = random.choice(nouns)

        if noun[0] in 'aeoiu':
            noun = ' an ' + noun
        else:
            noun = ' a ' + noun

        text = "You can get it " + p1 + "\n"
        text += "You can get it " + p2 + "\n"
        text += "You can get it " + p3 + noun + "\n"
        text += "Matter of fact I've got it now"

        return text
def generatePoem(scheme, starting):
    possible = []
    first_end_word = starting.split()[-1]
    rhyming_words = pronouncing.rhymes(first_end_word)
    most_sim = list(word_model.most_similar(first_end_word))
    for word, prob in most_sim:
        if word in rhyming_words:
            possible.append(word)
    if not possible:
        for word in rhyming_words:
            if word in word_vec.vocab:
                possible.append(word)
    if not possible:
        print("No rhyming words found! :(")
        sys.exit()

    scheme_dictionary = {}
    scheme_dictionary[scheme[0]] = possible
    new_words_list = []
    scheme = scheme[1:]
    for letter in scheme:
        if letter not in scheme_dictionary:
            new_word, prob = random.choice(most_sim)
            rhyming_words = pronouncing.rhymes(new_word)
            possible = [
                word for word in word_vec.vocab if word in rhyming_words
            ]
            while len(possible) < 1:
                new_word = random.choice(list(word_vec.vocab.keys()))
                rhyming_words = pronouncing.rhymes(new_word)
                possible = [
                    word for word in word_vec.vocab if word in rhyming_words
                ]
            new_words_list.append(new_word)
            scheme_dictionary[letter] = possible

    if not possible:
        print("No rhyming words found! :(")
        sys.exit()

    poem = starting + "\n"
    for letter in scheme:
        word = random.choice(scheme_dictionary.get(letter))
        rev_sent = generate_sent(word)
        sent = reverse_sentence(rev_sent)
        poem += sent + "\n"
    dir_name = "Generated_poems"
    root_dir = "/home"
    if (os.path.isdir(dir_name)):
        os.chdir(dir_name)
        with open("poem.txt", "w") as f:
            f.write(poem)
    else:
        os.mkdir(dir_name)
        os.chdir(dir_name)
        with open("poem.txt", "w") as f:
            f.write(poem)
    os.chdir(root_dir)
    return poem
Example #8
0
def get_rhymes(word):
    word2 = str(word).strip().lower()
    if rhymes(word2) == []:
        rhymelist = 'None - Is that an English word?'
    else:
        rhymelist = rhymes(word2)

    return rhymelist
def print_chorus(words_in_chorus, output, pos_dict):
    count = 0
    count1 = 0
    output.write("CHORUS:")

    for words in words_in_chorus:
        # output.write(words + " ")
        count += 1
        if count % 10 == 0:
            if count1 == 0:
                prev_word = words_in_chorus[count - 1]
                # print ("prev_word",prev_word)
                # idx+=random_idx+1
                rhymed_word = pronouncing.rhymes(prev_word)
                # print ("rhymed_word",rhymed_word)
                while not rhymed_word:
                    tag_word = nltk.pos_tag([prev_word])[0][1]
                    prev_word = random.choice(pos_dict[tag_word].keys())
                    # ix_word = generated[idx]
                    rhymed_word = pronouncing.rhymes(prev_word)
                    # idx+=1
                words1 = prev_word

                # print ("ix_word",ix_word)
            if count1:
                added_word = 0
                # print ("words",words)
                # print ("prev_word",prev_word)
                tag_word = nltk.pos_tag([prev_word])[0][1]
                # print ("tag_word",tag_word)
                rhymed_word = pronouncing.rhymes(prev_word)
                # print ("rhymed_word",rhymed_word)
                for word in rhymed_word:
                    if (nltk.pos_tag([word])[0][1]) == tag_word:
                        added_word = 1
                        words1 = word
                        break
                # print ("sent",sent)
                # print ("added_word",added_word)
                # if added_word==0:
                #     if not rhymed_word:
                #         sent+=[generated[random_idx+1]]
                #         idx+=random_idx+2
                #     else:
                #         sent+=[rhymed_word[0]]
                #         idx+=random_idx+1
                # else:
                #     idx+=random_idx+1
                count1 = 0
            else:
                # prev_word=ix_word
                # sent+=[ix_word]
                count1 = 1
            output.write(words1 + " ")
            # print ("words1",words1)
            output.write("\n")
        else:
            output.write(words + " ")
Example #10
0
def rhyme_score(line1, line2, alpha=0.4):
    word1 = re.sub(r"\W+", '', line1.split(" ")[-1]).lower().strip(".:;?!")
    word2 = re.sub(r"\W+", '', line2.split(" ")[-1]).lower().strip(".:;?!")
    if word2 in pronouncing.rhymes(word1) or word1 in pronouncing.rhymes(
            word2):
        return 1
    elif last_syllable(word1) == last_syllable(word1):
        return alpha
    else:
        return 0
Example #11
0
def twowordci(word1, word2):
    """Two word rhyme context independent[for all pronunciations] detection, returns bool"""
    from pronouncing import rhymes
    rhymesword1 = rhymes(word1)
    rhymesword2 = rhymes(word2)
    for value in rhymesword1:
        if value in rhymesword2:
            isrhyme = True
            return isrhyme
    isrhyme = False
    return isrhyme
 def test_rhymes(self):
     rhymes = pronouncing.rhymes("sleekly")
     expected = [
         'beakley', 'biweekly', 'bleakley', 'meekly', 'obliquely',
         'steakley', 'szekely', 'uniquely', 'weakley', 'weakly',
         'weekley', 'weekly', 'yeakley']
     self.assertEqual(expected, rhymes)
     # ensure correct behavior for words that don't rhyme
     rhymes = pronouncing.rhymes("orange")
     self.assertEqual([], rhymes)
     # ensure correct behavior for OOV words
     rhymes = pronouncing.rhymes("qwerasdfzxcv")
     self.assertEqual([], rhymes)
Example #13
0
def get_rhyme(rhyme_word, syllables_required, rhyming_model, syllable_count,
              syllable_pronounciation, rhyming_dictionary):
    rhyme_word_alt = remove_extension(rhyme_word)
    if rhyme_word_alt.upper() in syllable_pronounciation:
        pronounciation = syllable_pronounciation[rhyme_word_alt.upper()]
        last_occurence_syllable_unstressed = pronounciation.rfind("0")
        last_occurence_syllable_stressed = pronounciation.rfind("1")
        if last_occurence_syllable_stressed > last_occurence_syllable_unstressed:
            sub_pronounciation = pronounciation[:
                                                last_occurence_syllable_stressed]
        else:
            sub_pronounciation = pronounciation[:
                                                last_occurence_syllable_unstressed]
        space_index = sub_pronounciation.rfind(" ")
        last_syllable = pronounciation[space_index + 1:]
        rhymes = rhyming_model.rhyme_pick(last_syllable, rhyming_dictionary,
                                          syllables_required, syllable_count,
                                          syllable_pronounciation)
        for rhyme in rhymes:
            if rhyme in banned_end_words or rhyme == rhyme_word:
                rhymes.remove(rhyme)
        if len(rhymes) >= 1:
            rhyme = random.choice(rhymes)
        else:
            # No rhymes can be found from the rhyming dictionary, use RhymeBrain
            rhymes = rhyming_model.rhyme_brain(rhyme_word, syllables_required,
                                               syllable_pronounciation)
            if len(rhymes) >= 1:
                rhyme = random.choice(rhymes)
            # No rhymes can be found from RhymeBrain, use pronouncing
            else:
                rhymes = pronouncing.rhymes(rhyme_word)
                if len(rhymes) >= 1:
                    rhyme = random.choice(rhymes)
                else:
                    raise NoRhymeError("Cannot find a rhyming word.")
    else:
        # No rhymes can be found from the rhyming dictionary, use RhymeBrain
        rhymes = rhyming_model.rhyme_brain(rhyme_word, syllables_required,
                                           syllable_pronounciation)
        if len(rhymes) >= 1:
            rhyme = random.choice(rhymes)
        else:
            # No rhymes can be found from RhymeBrain, use pronouncing
            rhymes = pronouncing.rhymes(rhyme_word)
            if len(rhymes) >= 1:
                rhyme = random.choice(rhymes)
            else:
                raise NoRhymeError("Cannot find a rhyming word.")
    return rhyme.lower()
Example #14
0
def rhymeindex(lyrics):
	if str(artist) + ".rhymes" in os.listdir(".") and train_mode == False:
		print ("loading saved rhymes from " + str(artist) + ".rhymes")
		return open(str(artist) + ".rhymes", "r",encoding='utf-8').read().split("\n")
	else:
		rhyme_master_list = []
		print ("Building list of rhymes:")
		for i in lyrics:
			word = re.sub(r"\W+", '', i.split(" ")[-1]).lower()
			rhymeslist = pronouncing.rhymes(word)
			rhymeslistends = []      
			for i in rhymeslist:
				rhymeslistends.append(i[-2:])
			try:
				rhymescheme = max(set(rhymeslistends), key=rhymeslistends.count)
			except Exception:
				rhymescheme = word[-2:]
			rhyme_master_list.append(rhymescheme)
		rhyme_master_list = list(set(rhyme_master_list))
		reverselist = [x[::-1] for x in rhyme_master_list]
		reverselist = sorted(reverselist)
		rhymelist = [x[::-1] for x in reverselist]
		print("List of Sorted 2-Letter Rhyme Ends:")
		print(rhymelist)
		f = open(str(artist) + ".rhymes", "w", encoding='utf-8')
		f.write("\n".join(rhymelist))
		f.close()
		return rhymelist
Example #15
0
def rhyme(r, comment):
    print "String found in comment " + comment.id
    if comment.id in comment_replied:
        print "Skipping comment; already replied to."
    #Now, check to make sure we are not replying to ourselves!
    #elif comment.author == r.user.me():
    #print "Skipping; this is our own comment!"
    else:
        words = comment.body.split()
        index = 0
        for word in words:
            if "!rhyme" in word:
                break
            index = index + 1
        rhyme_word = words[index + 1]
        rhymes = pronouncing.rhymes(rhyme_word)
        if len(rhymes) > 0:
            reply = rhyme_word + " rhymes with " + random.choice(rhymes)
            reply += "\nThank you so much for using me!\n"
            reply += "Say hi to me by typing !hibot\n"
            reply += "Normal use: Type !rhyme followed by a word you wish to rhyme!\n"
            reply += "Secret command: To hear a Chuck Norris joke, comment !chucknorrisjoke anywhere in this subreddit!"

            comment.reply(reply)
            #Mark this comment as replied to!
            comment_replied.append(comment.id)
            print "Comment" + comment.id + " replied to!"

            #Now write this comment to our text file so we dont
            #reply to it in our next run
            with open("replied_comments.txt", "a") as output:
                output.write(comment.id + "\n")
Example #16
0
def classify_lines(lines):
    words = set(w for w in flatten_lines(lines)
                if get_word_type(w) is not None)
    database = {word: {} for word in words}

    for word, info in database.items():
        info['type'] = get_word_type(word)
        info['rhyming_words'] = set(
            pronouncing.rhymes(word)).intersection(words)

        info['begin_line_count'] = 0
        info['begin_line_prob'] = 0

    for l in lines:
        if not l:
            continue
        first_word = l[0]
        if not first_word in database:
            continue

        info = database[first_word]
        info['begin_line_count'] += 1

    for word, info in database.items():
        info['begin_line_prob'] = info['begin_line_count'] / len(words)

    return database
Example #17
0
def rhyme(rand):
    poem = "\n"
    print()
    f = open("dict/Poems/%s"%(poems[rand.pop()%len(poems)]),"r")
    poe = f.readlines()
    f.close()

    for i in range(len(poe)):
        poe[i] = re.sub('\n', 'X',poe[i])
        poe[i] = re.sub('[^A-Za-z0-9]+', ' ',poe[i])
        poe[i] = re.sub('X', '\n',poe[i])

    poe = ''.join(poe)
    poe = poe.lower()
    poe = re.sub('  ', '',poe)
    poe = poe.split("\n")
    for i in range(len(poe)):
        out = list()
        if i > 0:
            for word in poe[i].split():
                rhymes = pronouncing.rhymes(word)
                if len(rhymes) > 0:
                    out.append(rhymes[rand.pop() % len(rhymes)])
                else:
                    out.append(word)

            print(' '.join(out))
            poem += ' '.join(out)
        else:
            poem += poe[i]
            print(poe[i])

    tts = gTTS(text=poem, lang='en')
    tts.save("poem.mp3")
    os.system("poem.mp3")
Example #18
0
def rhymeindex(lyrics):
	if str(rapper) + ".rhymes" in os.listdir(".") and train == False:
		print "loading saved rhymes from " + str(rapper) + ".rhymes"
		return open(str(rapper) + ".rhymes", "r").read().split("\n")
	else:
		rhyme_master_list = []
		print "Alright, building the list of all the rhymes"
		for i in lyrics:
			word = re.sub(r"\W+", '', i.split(" ")[-1]).lower()
			rhymeslist = pronouncing.rhymes(word)
			rhymeslist = [x.encode('UTF8') for x in rhymeslist]
			rhymeslistends = []
			for i in rhymeslist:
				rhymeslistends.append(i[-2:])
			try:
				rhymescheme = max(set(rhymeslistends), key=rhymeslistends.count)
			except Exception:
				rhymescheme = word[-2:]
			rhyme_master_list.append(rhymescheme)
		rhyme_master_list = list(set(rhyme_master_list))

		reverselist = [x[::-1] for x in rhyme_master_list]
		reverselist = sorted(reverselist)

		rhymelist = [x[::-1] for x in reverselist]

		f = open(str(rapper) + ".rhymes", "w")
		f.write("\n".join(rhymelist))
		f.close()
		print rhymelist
		return rhymelist
Example #19
0
def myRhym(word):
    pron = pronouncing.rhymes(word)
    if len(pron) == 0:
        bupron = []
        i = 5
        while len(bupron) < 5:
            bupron = rhyme(word, i)
            if len(bupron) == 5:
                burpon = rhyme(word, i - 1)
                break
            i -= 1
        if word in bupron: bupron.remove(word)
        return burpon
    else:
        bupron = []
        i = 5
        while len(bupron) < 5:
            bupron = rhyme(word, i)
            if len(bupron) == 5:
                burpon = rhyme(word, i - 1)
                break
            i -= 1
        for w in bupron:
            if w not in pron and w != word:
                pron.append(w)
        if word in bupron: bupron.remove(word)
        return pron
def rhymeindex(lyrics):
	if str(artist) + ".rhymes" in os.listdir(".") and train_mode == False:
		print "loading saved rhymes from " + str(artist) + ".rhymes"
		return open(str(artist) + ".rhymes", "r").read().split("\n")
	else:
		rhyme_master_list = []
		print "Alright, building the list of all the rhymes"
		for i in lyrics:
			word = re.sub(r"\W+", '', i.split(" ")[-1]).lower()
			rhymeslist = pronouncing.rhymes(word)
			rhymeslist = [x.encode('UTF8') for x in rhymeslist]
			rhymeslistends = []
			for i in rhymeslist:
				rhymeslistends.append(i[-2:])
			try:
				rhymescheme = max(set(rhymeslistends), key=rhymeslistends.count)
			except Exception:
				rhymescheme = word[-2:]
			rhyme_master_list.append(rhymescheme)
		rhyme_master_list = list(set(rhyme_master_list))

		reverselist = [x[::-1] for x in rhyme_master_list]
		reverselist = sorted(reverselist)
		
		rhymelist = [x[::-1] for x in reverselist]

		f = open(str(artist) + ".rhymes", "w")
		f.write("\n".join(rhymelist))
		f.close()
		print rhymelist
		return rhymelist
Example #21
0
 def test_rhymes_for_single_pronunciation(self):
     rhymes = pronouncing.rhymes("sleekly")
     expected = [
         'beakley', 'bi-weekly', 'biweekly', 'bleakley', 'meekly',
         'obliquely', 'steakley', 'szekely', 'uniquely', 'weakley',
         'weakly', 'weekley', 'weekly', 'yeakley']
     self.assertEqual(expected, rhymes)
Example #22
0
def count_rhymes(lyrics_string):
    n_rhymes = 0,
    for index in range(1, len(lyrics_string)):
        if lyrics_string[index].split()[-1] in pronouncing.rhymes(
                lyrics_string[index - 1].split()[-1]):
            n_rhymes += 1
    return n_rhymes
def find_nearest(vec, prev_word, method='cosine'):
    if method == 'cosine':
        nearest_word = ""
        max_val = -1
        list_vec = []
        rhymed_words = pronouncing.rhymes(prev_word)
        for word in rhymed_words:
            try:
                val = np.dot(vec, glove_model[word])
                list_vec.insert(0, [val, word])
                if max_val < val:
                    max_val = val
                    nearest_word = word
            except Exception as e:
                pass
        sorted_list_vec = sorted(list_vec, key=lambda x: x[0])
        # if previous_word == sorted_list_vec[0][1]:
        #     return sorted_list_vec[1][0],sorted_list_vec[1][1]
        # else:
        #     return sorted_list_vec[0][0],sorted_list_vec[0][1]
        len_gen = len(rhymed_words)
        for y in range(len(sorted_list_vec)):
            flag = 0
            for x in rhymed_words:
                if x == sorted_list_vec[y][1]:
                    break
                flag += 1
            if flag == len_gen:
                return sorted_list_vec[y][0], sorted_list_vec[y][1]
    else:
        raise Exception(
            '{} is not an excepted method parameter'.format(method))
Example #24
0
def get_rhyme_scheme(last_words_per_line):
    """
    Convert a list of words to a rhyme scheme represented as a string, such as 'aabb' if the first two
    words rhyme, and the last two words rhyme.
    """
    alphabet = string.ascii_lowercase
    rhyme_scheme = np.empty(len(last_words_per_line), dtype=str)
    k = 0
    for i in range(len(last_words_per_line)):
        if rhyme_scheme[i] == '':
            if last_words_per_line[i] is not None:
                rhyme_scheme[i] = alphabet[k % 26]
                # determine rhyming words
                rhyme_list = pronouncing.rhymes(last_words_per_line[i])
                # if none of the rhyme words are found in the sentence, try with alternative pronounciations.
                if not np.any([x in rhyme_list for x in last_words_per_line]):
                    rhyme_list = rhymes_all(last_words_per_line[i])
                # find the matching rhyme words and edit the rhyme_scheme
                if np.any([x in rhyme_list for x in last_words_per_line]):
                    rhyme_scheme[(np.array(
                        [x in rhyme_list for x in last_words_per_line]) &
                                  (rhyme_scheme == ''))] = alphabet[k % 26]
                k += 1
            else:
                rhyme_scheme[i] = '?'

    return ''.join(rhyme_scheme)
Example #25
0
def rhyme_scheme(lines):
    scheme = '0'
    i = 1
    r_words = {}
    words = word_tokenize(lines[0])
    if words[-1] in string.punctuation or words[-1] == '...':
        r_word = words[-2]
    else:
        r_word = words[-1]
    r_words[r_word] = 0

    while i < len(lines):
        words = word_tokenize(lines[i])
        if words[-1] in string.punctuation or words[-1] == '...':
            r_word = words[-2]
        else:
            r_word = words[-1]
        rhymes = pronouncing.rhymes(r_word)
        new_rhyme = True
        for j in r_words.keys():
            if j in rhymes:
                scheme = scheme + str(r_words[j])
                new_rhyme = False
        if new_rhyme:
            r_words[r_word] = len(r_words)
            scheme = scheme + str(r_words[r_word])
        i += 1
    return scheme
Example #26
0
	def findRhymingWord(self, inputWord):
		rhymingWords = pronouncing.rhymes(inputWord)
		maxWords = min(5, len(rhymingWords))
		if(maxWords == 0):
			return "hello"
		randomNum = (random.randrange(0,maxWords))
		return rhymingWords[randomNum]
def check_tweet(text, exclusions=[]):
    lower = text.lower()
    # remove newline
    lower = lower.replace('\n', ' ')

    # dont include retweets or @ mentions
    if (starts_with(lower, 'rt') or starts_with(lower, '@')
            or starts_with(lower, '.')):
        return False

    # throw out tweets with links
    if ('http' in lower):
        return False

    lower = cleanup_text(lower, exclusions)

    # make sure things stay reasonably short
    if num_syllables(lower) > 16:
        return False

    # check to be sure that the last word can be rhymed to
    last_word = lower.split()[-1].split('-')[-1]
    if len(pronouncing.rhymes(last_word)) == 0:
        return False

    return True
Example #28
0
def list_phonetic_rhymes(word):
    list_phonetic = []
    for word in pronouncing.rhymes(word):
        phonetic = p.convert(word)
        if "*" not in phonetic:
            list_phonetic.append(phonetic)
    return list_phonetic
Example #29
0
def phonetic_weight(name_to_remember, current_trigger_word,pw):
#create metaphone codes without the first unnecessary letters
    if name_to_remember[0] == ('w' or 'q'):
        w1_without_fl = phonetics.metaphone(name_to_remember[2:])
    else:
        w1_without_fl = phonetics.metaphone(name_to_remember[1:]) 
    if current_trigger_word[0] == ('w' or 'q'):
        w2_without_fl = phonetics.metaphone(current_trigger_word[2:])
    else: 
        w2_without_fl = phonetics.metaphone(current_trigger_word[1:]) 
#calculate the levenshtein distance between the two metaphone codes
    score_without_fl = enchant.utils.levenshtein(w1_without_fl, w2_without_fl)

#create a list of all known rhyming words from the pronouncing library
    checklist = pronouncing.rhymes(name_to_remember)

#check if the candidate trigger word is in the list of know rhyming words 
    if current_trigger_word in checklist:
        return pw
#otherwise calculate its phonetic similarity using the users pw(phonetic weight) and ..
#..the levenshtein/metaphone score
    elif score_without_fl == 0:
        return pw/1.5
    else: 
        return pw/(score_without_fl+1)

#the_list = create_output_list_v3(doc,start_word, pw, slw, flw, pwsw)
                    
Example #30
0
 def rhyme(self, inp, level, exact=True):
     inp = inp.lower()
     entries = nltk.corpus.cmudict.entries()
     syllables = [(word, syl) for word, syl in entries if word == inp]
     strip_stress = lambda syl: [s[0:2] if len(s) > 2 else s for s in syl]
     strip = lambda syl: [
         strip_stress(s) for s in syl if s == 'L' or s[0:2] in self.VOWELS
     ]
     rhyme_check = lambda test, syl, f: all([
         len(f(test)) >= i and f(test)[-i] == f(syl)[-i]
         for i in range(1,
                        min(level, len(f(syl)),
                            len(f(test)) + 1) + 1)
     ])
     vowel_end = lambda pron: len(pron[-2]) > 2 and pron[-1] == 'Z' or len(
         pron[-1]) > 2 if len(pron) > 2 else len(pron[-1])
     vowel_check = lambda test, syl: vowel_end(test) if vowel_end(
         syl) else True
     rhymes = []
     for (word, syllable) in syllables:
         rhymes += [
             word for word, pron in entries if vowel_check(pron, syllable)
             and rhyme_check(pron, syllable, strip)
         ]
     rhymes.append(inp)
     return set(rhymes) | set(pronouncing.rhymes(inp))
Example #31
0
def make_poem_lines(questions, num_of_couplets):
    """take in questions, make poem"""
    keys = list(questions.keys())
    #print(keys)
    poem = []
    found = False

    for index in range(0, len(keys)):
        #print("-----------------" + str(keys[index])+ "----------------------")
        same_length_poem = []
        if keys[index] > 3 and keys[index] < 12:
            same_length_questions = list(set(questions[keys[index]]))
            used = set()
            for i in range(0, len(same_length_questions)):
                a_question = same_length_questions[i]
                for j in range(i + 1, len(same_length_questions)):
                    another_question = same_length_questions[j]
                    if a_question in used or another_question in used:
                        continue
                    if a_question.split()[-1] in pronouncing.rhymes(
                            another_question.split()[-1]):
                        same_length_poem.append([a_question, another_question])
                        used.add(a_question)
                        used.add(another_question)
        if len(same_length_poem) > num_of_couplets:
            poem.append(same_length_poem)
    return poem
def get_rhyme(rhyme_word, syllables_required, rhyming_model, syllable_count, syllable_pronounciation, rhyming_dictionary):
  rhyme_word_alt = remove_extension(rhyme_word)
  if rhyme_word_alt.upper() in syllable_pronounciation:
    pronounciation = syllable_pronounciation[rhyme_word_alt.upper()]
    last_occurence_syllable_unstressed = pronounciation.rfind("0")
    last_occurence_syllable_stressed = pronounciation.rfind("1")
    if last_occurence_syllable_stressed > last_occurence_syllable_unstressed:
      sub_pronounciation = pronounciation[:last_occurence_syllable_stressed]
    else:
      sub_pronounciation = pronounciation[:last_occurence_syllable_unstressed]
    space_index = sub_pronounciation.rfind(" ")
    last_syllable = pronounciation[space_index + 1:]
    rhymes = rhyming_model.rhyme_pick(last_syllable, rhyming_dictionary, syllables_required, syllable_count, syllable_pronounciation)
    for rhyme in rhymes:
      if rhyme in banned_end_words or rhyme == rhyme_word:
        rhymes.remove(rhyme)
    if len(rhymes) >= 1:
      rhyme = random.choice(rhymes)
    else:
      # No rhymes can be found from the rhyming dictionary, use RhymeBrain
      rhymes = rhyming_model.rhyme_brain(rhyme_word, syllables_required, syllable_pronounciation)
      if len(rhymes) >= 1:
        rhyme = random.choice(rhymes)
      # No rhymes can be found from RhymeBrain, use pronouncing
      else:
        rhymes = pronouncing.rhymes(rhyme_word)
        if len(rhymes) >= 1:
          rhyme = random.choice(rhymes)
        else:
          raise NoRhymeError("Cannot find a rhyming word.")
  else:
    # No rhymes can be found from the rhyming dictionary, use RhymeBrain
    rhymes = rhyming_model.rhyme_brain(rhyme_word, syllables_required, syllable_pronounciation)
    if len(rhymes) >= 1:
      rhyme = random.choice(rhymes)
    else:
      # No rhymes can be found from RhymeBrain, use pronouncing
      rhymes = pronouncing.rhymes(rhyme_word)
      if len(rhymes) >= 1:
        rhyme = random.choice(rhymes)
      else:
        raise NoRhymeError("Cannot find a rhyming word.")
  return rhyme.lower()
 def test_rhymes_for_multi_pronunciation(self):   
     # ensure correct behavior for words that have multiple pronunciations
     rhymes = pronouncing.rhymes("dove")
     expected = [
         "above", "belove", "boeve", "bove", "clove", "cove",
         "deneuve", "drove", "glove", "gov", "gove", "grove",
         "hove", "labauve", "labov", "labove", "love", "nov",
         "o'glove", "of", "rove", "shove", "soave", "stove",
         "strove", "thereof", "throve", "tov", "trove", "vanhove",
         "wove"]
     self.assertEqual(expected, rhymes)
def rhyme(line, rhyme_list):
	word = re.sub(r"\W+", '', line.split(" ")[-1]).lower()
	rhymeslist = pronouncing.rhymes(word)
	rhymeslist = [x.encode('UTF8') for x in rhymeslist]
	rhymeslistends = []
	for i in rhymeslist:
		rhymeslistends.append(i[-2:])
	try:
		rhymescheme = max(set(rhymeslistends), key=rhymeslistends.count)
	except Exception:
		rhymescheme = word[-2:]
	try:
		float_rhyme = rhyme_list.index(rhymescheme)
		float_rhyme = float_rhyme / float(len(rhyme_list))
		return float_rhyme
	except Exception:
		return None
Example #35
0
 def test_rhymes(self):
     rhymes = pronouncing.rhymes("sleekly")
     expected = [
         "beakley",
         "biweekly",
         "bleakley",
         "meekly",
         "obliquely",
         "steakley",
         "szekely",
         "uniquely",
         "weakley",
         "weakly",
         "weekley",
         "weekly",
         "yeakley",
     ]
     self.assertEqual(expected, rhymes)
Example #36
0
def findRhymes(word):
   return pronouncing.rhymes(word)
Example #37
0
def is_negated(word1, word2):
	# check to see if the rhyme is just the other word with a negative
	# prefix stuck on. stuff like "too unhappy to be happy" is crappy
	for prefix in prefixes:
		if word1 == prefix + word2 or word2 == prefix + word1:
			return True
	return False

while not word2:
	rhymes = []

	# pick random words until we find one with at least one rhyme
	while len(rhymes) < 1:
		word1 = str(random.choice(adjectives))
		print word1
		rhymes = pronouncing.rhymes(word1)
		print rhymes
		print len(rhymes)

	# we're about to iterate through the rhyme list and post the
	# first suitable rhyme we find. thus, we need to randomize the
	# order of the list; otherwise the same word will always end up
	# with the same rhyme.
	random.shuffle(rhymes)

	# try each rhyme in the list until we find one that is an
	# adjective but is not just our first word with a prefix that
	# negates it
	for attempt in rhymes:
		attempt = str(attempt)
		print "Trying %s." % attempt
Example #38
0
import double_metaphone
import collections
import pronouncing
import editdistance

WORD = 'nakedness'
WORD = "untrimmed"
WORD = 'factorize'
WORD = 'obscurantism'
WORD = 'polyhedral'

print pronouncing.rhymes(WORD)

metaphone_to_word = collections.defaultdict(set)
for word in pronouncing.pronunciations:
    encoded = word.encode('utf8')
    for dm in double_metaphone.dm(encoded):
        if dm:
            metaphone_to_word[dm].add(word)
            
by_distance = []
for word in pronouncing.pronunciations:
    distance = editdistance.eval(word, WORD)
    if word.startswith(WORD[0]):
        distance -= 1
    if word.endswith(WORD[-1]):
        distance -= 1 
    character_difference = abs(len(word) - len(WORD))
    by_distance.append((distance, character_difference, word))

by_distance.sort()
 def test_rhymes_for_non_rhyming(self):
     # ensure correct behavior for words that don't rhyme
     rhymes = pronouncing.rhymes("orange")
     self.assertEqual([], rhymes)
Example #40
0
import sys
import pymongo
from models import Poem
import pprint
import utils
import pronouncing

print pronouncing.rhymes('a')
print pronouncing.rhymes('the')
raise 'STOp'

db = pymongo.MongoClient().poetry

document = db.poems.find_one({'_id': '10'})
poem = Poem(document, db)

pprint.pprint(poem.get_rhymes())
poem.set_rhymes()
 def test_rhymes_for_out_of_vocab(self):
     # ensure correct behavior for OOV words
     rhymes = pronouncing.rhymes("qwerasdfzxcv")
     self.assertEqual([], rhymes)