示例#1
0
    def song_from_poem(self, text_file):
        poem = Poem(text_file)  # read the file as a Poem object

        # choose a root to our arpeggio
        root = 60 + (poem.total_syllables() % 12)

        # iterate over each syllable
        for line in poem.lines:
            chord_root = root + self._scale_intervals[
                (self.sum_string(str(line)) % 8)]
            for word in line.words:
                if chord_root == 1 or chord_root == 3 or chord_root == 5:
                    chord_type = "major"
                else:
                    chord_type = "minor"

                # determine pitch by summing characters
                pitch = (self.sum_string(str(word))) % len(
                    self._arpeggios[chord_type])

                # determine duration by length of syllable
                duration = (word.syllables % 3) + 1

                # add the new note to our local list of notes
                self.notes.append(
                    self.Note(chord_root + self._arpeggios[chord_type][pitch],
                              duration))
示例#2
0
def pogen(syl, time, genre, sBool):
    # Initialize Poem class and generate the poem
    category = time + '_' + genre
    corpus = PoemUtility.tokenize(category + '.csv')
    matrix = MarkovMatrix(corpus, 2)

    poeminstance = Poem(matrix, syl, category, sBool)
    print("\nPlease wait a few seconds, PoGen is thinking...")
    poem = poeminstance.generatePoem()

    print("\n***********************************************\n")
    print(poem)
    print("***********************************************\n")
def write_poetry():
    """Writes and evaluates 10 new poems. Returns the best one.
        Returns:
            poems (list): 10 new poems.
    """
    x = 0
    new_poems = []
    frags = call_fragments()
    verbs = get_verbs(frags)
    nouns = get_noun_phrases(frags)
    print("Writing poems...")

    while x < 10:
        num_nouns = random.randint(1, 20)
        num_verbs = random.randint(1, 20)
        # Makes a proto-poem (nouns and verbs in a list).
        list_poem = make_list_poem(verbs, nouns, num_nouns, num_verbs)
        line_breaks = random.randint(0, 15)
        y = 0
        while y < line_breaks:
            list_poem.insert(random.randint(0, len(list_poem)), "\n]")
            y += 1
        text = " ".join(list_poem)
        new_poem = Poem(text, num_nouns, num_verbs)
        new_poems.append(new_poem)
        x += 1

    return new_poems
def generate_poem(ngrams, all_comments, degree):
    '''Creates a poem object with 5 lines of content'''
    
    poem_content = []
    for i in range(5):
        line = generate_line(ngrams, all_comments, DEGREE)
        poem_content.append(line)
    
    poem = Poem(poem_content)
    return poem
def make_poems(poem_list):
    """Converts poem strings into poem objects.
        Args:
            poem_list (list): list of poems (as strings)

        Returns:
            poems (list): list of poems (as Poem objects)
    """
    poems = []
    for text in poem_list:
        poems.append(Poem(text, num_nouns = None, num_verbs = None))
    return poems
def main():
    dataset = []
    i = 1
    with open('poetry_dataset.csv', 'wt') as pcsv:
        p_writer = csv.writer(pcsv, delimiter='\t')
        p_writer.writerow(
            ['Order', 'Id', 'Author', 'Url', 'Title', 'Text', 'Word_Count'])
        for order in range(1, 84):
            print(order)
            index_page = 'http://www.chinapoesy.com/XianDaiList_%d.html' % order  # 83 index pages at most
            peom_link_list = parseIndexPage(index_page)
            for poem_link in peom_link_list:
                poem = Poem(poem_link)
                p_writer.writerow([
                    i, poem.id, poem.author, poem.poem_url, poem.title,
                    poem.text, poem.wordCount
                ])
                i += 1
                #print(poem.id)
                #print(poem.author)
                #print(poem.poem_url)
                print(poem.title)
                #print(poem.text.encode('gbk', 'ignore').decode('gbk').split())
        print(i)
示例#7
0
CONSUMER_KEY = environ['CONSUMER_KEY']
CONSUMER_SECRET = environ['CONSUMER_SECRET']
ACCESS_KEY = environ['ACCESS_KEY']
ACCESS_SECRET = environ['ACCESS_SECRET']

# Connect to API
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)

# Connect to database
all_non_tweeted_poems = Poem_database.query.filter_by(tweeted=False).all()
random_poem = random.choice(all_non_tweeted_poems)

poem = Poem(author=random_poem.author,
            title=random_poem.title,
            content=random_poem.content)

now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print(f"Current Time : {current_time}")

print(f"Poem {poem.title} \n {poem.content}")
poem.parse()
print(f"Parsed poem {poem.title}: \n ")
print(*poem.parsed_content, sep="\n + ")

if __name__ == "__main__":
    try:
        poem.tweet(api)
        random_poem.tweeted = True
示例#8
0
    "la musique, la chevalerie, l’ascétisme, ont pu ajouter à l’amour) découle non d’un idéal de beauté qu’ils ont "
    "élu, mais d’une maladie inguérissable ; comme les juifs encore (sauf quelques-uns qui ne veulent fréquenter que "
    "\n His many legs, pitifully thin compared with the size of the rest of "
    "him, waved about helplessly as he looked. \"What's happened to me? \" he thought. It wasn't a dream. His room, "
    "a proper human room although a little too small, ze2o9pDPNRAyH0oGyL8nuQL4uoiVKO4aR1w4ItcN1lEe3WdZcYLNqSkHYzQZi817CcurgjPEbbhkjIGhxr6PjVnq4zXxGF4deTdebx9Cox1YPjd2ND0"
    "A4syUxeQjPqoeVosodw98cBmugixPPl3poPeJJMzde9Dp6U0qvp3NLUGCWDFdEyWwyWim7UHoUmcD1dKAt5RRaROZdXdwKjAKcPE913RoktFImpSpTH "
    "csuB2RdluJDNds5N8XHZ1YWSswnu2UigQAJRhLs1bUwwsAZttvCjBJn4fjA2 lay peacefully between its four familiar walls."
]

title_tests = [
    "Bannières de mai", "Automne", "Emma", "Le fils des armures", "L'abandon",
    "Aux Champs Élyséens", "Le confiteor de l'artiste", "La Gitana"
]

for test in title_tests:
    random_poem = Poem_database.query.filter_by(title=test).all()[0]
    poem = Poem(author=random_poem.author,
                title=random_poem.title,
                content=random_poem.content)
    print(f"Poem {poem.title}")
    poem.parse()
    print("Parsed poem :")
    print(*poem.parsed_content, sep="\n +")

for test in test_poems:
    print("\n\n\n")
    poem = Poem(content=test)
    poem.parse()
    print("Parsed poem :")
    print(*poem.parsed_content, sep="\n +")