Created
May 7, 2015 13:05
-
-
Save sunny/3397136edd65c0d4695f to your computer and use it in GitHub Desktop.
Markov
This file contains hidden or 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
# Get phrases | |
phrases = File.readlines('phrases.txt') | |
.map { |p| p.gsub(/["()*]/, '') } | |
.map { |p| p.gsub(/ +/, ' ').strip } | |
.reject { |p| p.split(' ').size < 2 } | |
.uniq | |
# Get first words | |
starters = phrases.map { |p| p.split(' ').first } | |
# Create a chain { key => [word1, word2] } | |
chain = {} | |
phrases.each do |phrase| | |
words = phrase.split(' ') | |
words.each_with_index do |word, index| | |
next_word = words[index + 1] | |
chain[word] ||= [] | |
chain[word] << next_word | |
end | |
end | |
10.times do | |
phrase = [] | |
# first word from starters | |
word = starters.sample | |
while word | |
phrase << word | |
# next word from the chain | |
word = chain[word].sample | |
end | |
phrase = phrase.join(' ') | |
puts phrase unless phrases.include?(phrase) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment