Created
June 4, 2013 07:30
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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([email protected])] | |
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