ChainGang chain algorithm package

This is the place to post any code that you want to share with the community. Only completed scripts should be posted here.

ChainGang chain algorithm package

Postby XndrK » Mon Apr 14, 2014 9:12 pm

I was browsing on GitHub and I found a Markov chain word generator, which inspired me to make my own. I tried making a fork of his, but I decided to write one from scratch instead and consult that one if I couldn't remember how to do something. I finished it, and decided to make a whole bunch of chains and generators, but I haven't gotten around to it yet, but I have the Markov chain done.

https://github.com/4of92000/ChainGang

If there are any problems, let me know. If you want to develop, I'll get you set up.

CODE:
Code: Select all
"""This is a simple Markov chain text algorithm
that uses a user-defined corpus. This project is based on,
but is not a fork of, tedlee/markov on GitHub."""

import random

class Markov:
   def __init__(self, corpus):
      """Initializer function
      """
      self.corpus = corpus
      self.cache = {}
      self.word_list = self.corpus.split(" ")
      self.list_size = len(self.word_list)
   
   def words_iter(self):
      if len(self.word_list) < 3:
         print("I'm sorry, the corpus is too short.")
         return # end function
      
      tuple_list = zip(self.word_list, self.word_list[1:], self.word_list[2:])
      for tupl in tuple_list:
         yield tupl
      
   def setup_cache(self):
      for word1, word2, word3 in self.words_iter():
         key = word1, word2
         
         # if key already exists, append word to key
         if key in self.cache:
            self.cache[key].append(word3)
         # if key doesn't exist, make a new one
         else:
            self.cache[key] = [word3]
   
   def generate(self, size=50):
      
      self.setup_cache()
      
      # first word picker
      seed = random.randrange(0, self.list_size - 2)
      word1, word2 = self.word_list[seed] + self.word_list[seed+1]
      
      # corpus generator
      new_corpus = []
      
      # maker function
      for i in range(size):
         # append word to the corpus and pick the next one
         new_corpus.append(word1)
         word1, word2 = word2, random.choice(self.cache[(word1, word2)])
      
      # add last word
      new_corpus.append(word2)
      
      # put all the words together and print them
      print(" ".join(new_corpus))

# test code
corpus = """
Four score and seven years ago our fathers brought forth, on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.

Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this.

But, in a larger sense, we can not dedicate—we can not consecrate—we can not hallow—this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us—that from these honored dead we take increased devotion to that cause for which they here gave the last full measure of devotion—that we here highly resolve that these dead shall not have died in vain—that this nation, under God, shall have a new birth of freedom—and that government of the people, by the people, for the people, shall not perish from the earth.
"""

markov_corpus = Markov(corpus)

size = 80

markov_corpus.generate(size)
Last edited by stranac on Mon Apr 14, 2014 9:41 pm, edited 1 time in total.
Reason: Included code, since it's a single file.
Proverbs 26:14 describes me a bit too well.

Version: Python 2.7.5

https://github.com/4of92000
https://github.com/PythonForum/
User avatar
XndrK
 
Posts: 173
Joined: Sat Jun 15, 2013 7:57 pm

Re: ChainGang chain algorithm package

Postby stranac » Mon Apr 14, 2014 9:39 pm

Haven't really taken a close look, but I noticed a few things.
  • You're using tabs for indentation :/
  • This:
    Code: Select all
          tuple_list = zip(self.word_list, self.word_list[1:], self.word_list[2:])
          for tupl in tuple_list:
             yield tupl

    is pretty much the same as:
    Code: Select all
    return zip(words, words[1:], words[2:])
  • You assign self.corpus, but you don't really need it as an instance attribute
  • In words_iter(), you should raise an exception. The way your code is right now, a message would be printed, and then an exception would happen in a completely different place.
  • I would also return a string from generate(), instead of printing it.
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 1246
Joined: Thu Feb 07, 2013 3:42 pm

Re: ChainGang chain algorithm package

Postby XndrK » Mon Apr 14, 2014 11:25 pm

Do you have a GitHub account? If so, I can add you as a contributor.
Proverbs 26:14 describes me a bit too well.

Version: Python 2.7.5

https://github.com/4of92000
https://github.com/PythonForum/
User avatar
XndrK
 
Posts: 173
Joined: Sat Jun 15, 2013 7:57 pm

Re: ChainGang chain algorithm package

Postby stranac » Tue Apr 15, 2014 7:42 am

Not really interested in contributing to markov chain generator, sorry.
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 1246
Joined: Thu Feb 07, 2013 3:42 pm

Re: ChainGang chain algorithm package

Postby XndrK » Tue Apr 15, 2014 7:42 pm

Okay. I am going to add other chain algorithms too, so... if you are (or anyone else is) interested.
Proverbs 26:14 describes me a bit too well.

Version: Python 2.7.5

https://github.com/4of92000
https://github.com/PythonForum/
User avatar
XndrK
 
Posts: 173
Joined: Sat Jun 15, 2013 7:57 pm


Return to Completed Scripts

Who is online

Users browsing this forum: Baidu [Spider] and 2 guests