Created
June 16, 2015 03:04
-
-
Save drichert/c49f8f466c7abd37addf to your computer and use it in GitHub Desktop.
Render Wuthering Heights in substring matched, randomly hyponymized trigrams
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
require "treat" | |
include Treat::Core::DSL | |
text = File.read("wuthering-heights.txt").gsub(/\n/, " ").split(/\s+/) | |
trigrams = {} | |
headings = [] | |
text.each_with_index do |word, ndx| | |
st = (ndx + 1) % text.length | |
en = (ndx + 3) % text.length | |
if !trigrams[word] | |
trigrams[word] = [] | |
end | |
trigram = [] | |
3.times do |n| | |
trigram << text[(ndx + 1 + n) % text.length] | |
end | |
trigrams[word] << trigram | |
end | |
144.times do | |
root_word = text.sample | |
until headings.none? {|h| h =~ /#{Regexp::escape(root_word)}/i } | |
root_word = text.sample | |
end | |
headings << root_word | |
puts "\n\n#{root_word}\n\n" | |
3.times do | |
last_word = root_word | |
buffer = [] | |
36.times do | |
possible = [] | |
trigrams.keys.select {|k| k =~ /#{Regexp::escape(last_word)}/i }.map do |k| | |
possible.push(*trigrams[k]) | |
end | |
buffer << possible.sample | |
last_word = buffer.flatten.last | |
end | |
output = buffer.flatten.map do |w| | |
w = w.gsub /\A(\W*?)([\w']+)(\W*?)\z/ do |m| | |
hyps = word($2).hyponyms | |
"#{$1}#{hyps.empty? ? $2 : hyps.sample }#{$3}" | |
end | |
end | |
puts output.join(" ") + "\n\n" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wuthering Heights by Emily Brontë