Skip to content

Instantly share code, notes, and snippets.

@matsadler
Created July 25, 2012 09:15
Show Gist options
  • Save matsadler/3175229 to your computer and use it in GitHub Desktop.
Save matsadler/3175229 to your computer and use it in GitHub Desktop.
class Markov
attr_reader :order, :phrases
def initialize(corpus=[], order=3)
@order = order
@phrases = Hash.new {|h,k| h[k] = []}
add(corpus)
end
def add(corpus)
corpus = read_if_file(corpus)
corpus.each_with_index do |word, index|
phrase = corpus[index, order]
phrases[phrase] << corpus[index + order]
end
end
def generate(max=100)
seed = @phrases.keys.sample
output = []
max.times do
options = phrases[seed]
output << seed.shift
seed.push(options[rand(options.length)])
break if seed.compact.empty?
end
output.join(" ")
end
private
def read_if_file(object)
object = File.open(File.expand_path(object)) if object.respond_to?(:to_str)
if object.respond_to?(:each_line)
array = []
object.each_line {|line| array.push(*line.scan(/\S+/))}
object.close if object.respond_to?(:close)
object = array
end
object
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment