Created
November 24, 2009 12:40
-
-
Save pjaspers/241847 to your computer and use it in GitHub Desktop.
A class to generate a Haiku in ruby (prototype for haikuherman.eu)
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 'lingua/en/readability' | |
class Haiku | |
def initialize(text) | |
@report = Lingua::EN::Readability.new(text) | |
@used_words = Array.new | |
end | |
def get_most_used_words(words) | |
top_words = Array.new | |
words.sort{|a,b| a[1]<=>b[1]}.slice(words.length/2..words.length).each do |a| | |
top_words << a[0].downcase | |
end | |
return top_words | |
end | |
def get_random_word(words, max_syll) | |
word = words[rand(words.length)] | |
if Lingua::EN::Readability.new(word).num_syllables > max_syll or @used_words.include?(word) | |
word = get_random_word(words, max_syll) | |
end | |
return word | |
end | |
def generate_line(number_of_syllables) | |
most_used_words = get_most_used_words(@report.frequencies) | |
line = "" | |
n_syll = 0 | |
while n_syll < number_of_syllables | |
max_syll = number_of_syllables - n_syll | |
word = get_random_word(most_used_words, max_syll) | |
@used_words << word | |
word_syll = Lingua::EN::Readability.new(word).num_syllables | |
n_syll += word_syll | |
(line.length == 0 ? line << "#{word}": line << " #{word}") | |
end | |
return line << "(#{n_syll})" | |
end | |
def print_report | |
puts @report.report | |
puts get_most_used_words(@report.frequencies) | |
end | |
def print | |
puts generate_line(5).capitalize | |
puts generate_line(7) | |
puts generate_line(5) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment