Skip to content

Instantly share code, notes, and snippets.

@mdunsmuir
Created June 4, 2013 07:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdunsmuir/5704221 to your computer and use it in GitHub Desktop.
Save mdunsmuir/5704221 to your computer and use it in GitHub Desktop.
was bored, so random text generator (don't run james joyce's dirty letters through it)
# parse input
input = IO.read(ARGV.shift)
scanned = input.scan(/([A-Z].+?)([.?!])/).collect{ |arr| arr.join(" ").split }
words = Hash.new # store the successive probabilities of words
firstcount = 0
firsthash = Hash.new(0) # store the initial words' probabilities
scanned.each do |sentence|
last = sentence.shift
firsthash[last] += 1
while current = sentence.shift
words[last] ||= Hash.new(0)
words[last][current] += 1
last = current
end
end
class MarkovNode < String
def initialize(word, hash)
super(word)
@next = Array.new
hash.each do |word, num|
num.times{ @next << word }
end
end
def get_next
if @next.size > 0
@next[rand(0...@next.size)]
else
throw :done
end
end
def MarkovNode.iterate(first, all)
words = [first]
catch :done do
while true
n = words.last.get_next
if /[.!?]/.match(n)
words << n
throw :done
else
words << all[n]
end
end
end
return words[1..-1]
end
def inspect
puts @next.inspect
end
end
nodes = Hash.new
words.each do |word, hash|
node = MarkovNode.new(word, hash)
nodes[node] = node
end
first = MarkovNode.new("first", firsthash)
#puts first.inspect
10.times do
puts MarkovNode.iterate(first, nodes).join(" ")
puts
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment