Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class MarkovChain
- def initialize(text)
- @words = Hash.new
- wordlist = text.split
- wordlist.each_with_index do |word, index|
- add(word, wordlist[index + 1]) if index <= wordlist.size - 2
- end
- end
- def add(word, next_word)
- @words[word] = Hash.new(0) if !@words[word]
- @words[word][next_word] += 1
- end
- def get(word)
- return "" if !@words[word]
- followers = @words[word]
- sum = followers.inject(0) {|sum,kv| sum += kv[1]}
- random = rand(sum) + 1
- partial_sum = 0
- next_word = followers.find do |word, count|
- partial_sum += count
- partial_sum >= random
- end.first
- next_word
- end
- def generate_text(sentences)
- text = ""
- word = @words.keys[rand(@words.length)]
- word.gsub(/./, '')
- until text.count(".") == sentences
- text << word << " "
- word = get(word)
- end
- return text.gsub(/"/, '') << "\n"
- end
- end
- mc = MarkovChain.new(File.read('bible.txt'))
- puts mc.generate_text(2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement