Skip to content

Instantly share code, notes, and snippets.

@drichert
Created June 16, 2015 03:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drichert/c49f8f466c7abd37addf to your computer and use it in GitHub Desktop.
Save drichert/c49f8f466c7abd37addf to your computer and use it in GitHub Desktop.
Render Wuthering Heights in substring matched, randomly hyponymized trigrams
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
@drichert
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment