Advertisement
Guest User

markov chain

a guest
May 1st, 2014
323
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 0.93 KB | None | 0 0
  1. class MarkovChain
  2.     def initialize(text)
  3.         @words = Hash.new
  4.         wordlist = text.split
  5.         wordlist.each_with_index do |word, index|
  6.             add(word, wordlist[index + 1]) if index <= wordlist.size - 2
  7.         end
  8.     end
  9.  
  10.     def add(word, next_word)
  11.         @words[word] = Hash.new(0) if !@words[word]
  12.         @words[word][next_word] += 1
  13.     end
  14.  
  15.     def get(word)
  16.         return "" if !@words[word]
  17.         followers = @words[word]
  18.         sum = followers.inject(0) {|sum,kv| sum += kv[1]}
  19.         random = rand(sum) + 1
  20.         partial_sum = 0
  21.         next_word = followers.find do |word, count|
  22.             partial_sum += count
  23.             partial_sum >= random
  24.         end.first
  25.         next_word
  26.     end
  27.  
  28.     def generate_text(sentences)
  29.         text = ""
  30.         word = @words.keys[rand(@words.length)]
  31.         word.gsub(/./, '')
  32.         until text.count(".") == sentences
  33.             text << word << " "
  34.             word = get(word)
  35.         end
  36.         return text.gsub(/"/, '') << "\n"
  37.     end
  38. end
  39.  
  40. mc = MarkovChain.new(File.read('bible.txt'))
  41. puts mc.generate_text(2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement