Class: Markov::Generate
- Inherits:
-
Object
- Object
- Markov::Generate
- Defined in:
- lib/markov/generate.rb
Instance Attribute Summary collapse
-
#length ⇒ Object
readonly
Returns the value of attribute length.
-
#start ⇒ Object
readonly
Returns the value of attribute start.
-
#weight ⇒ Object
readonly
Returns the value of attribute weight.
Instance Method Summary collapse
- #current_word ⇒ Object
-
#initialize(dbname, options = {}) ⇒ Generate
constructor
A new instance of Generate.
- #lookup(word, table) ⇒ Object
- #next_word ⇒ Object
- #text ⇒ Object
Constructor Details
#initialize(dbname, options = {}) ⇒ Generate
Returns a new instance of Generate.
6 7 8 9 10 11 12 |
# File 'lib/markov/generate.rb', line 6 def initialize dbname, ={} @length = [:length] || 200 @weight = [:weight] || 1.2 @start = [:start] || "The" @table = [:table] @db = DB.new(dbname: dbname, chunk: [:chunk] || 4) end |
Instance Attribute Details
#length ⇒ Object (readonly)
Returns the value of attribute length.
4 5 6 |
# File 'lib/markov/generate.rb', line 4 def length @length end |
#start ⇒ Object (readonly)
Returns the value of attribute start.
4 5 6 |
# File 'lib/markov/generate.rb', line 4 def start @start end |
#weight ⇒ Object (readonly)
Returns the value of attribute weight.
4 5 6 |
# File 'lib/markov/generate.rb', line 4 def weight @weight end |
Instance Method Details
#current_word ⇒ Object
14 15 16 |
# File 'lib/markov/generate.rb', line 14 def current_word @current_word = @word || @start end |
#lookup(word, table) ⇒ Object
25 26 27 28 29 30 31 32 33 |
# File 'lib/markov/generate.rb', line 25 def lookup word, table @lookup = @db.lookup(word, table) { suffices: @lookup.map { |s| s[0] }, probability: @lookup.map.each_with_index { |c,i| [ (c[1].to_i ** @weight).round.times.inject([]){ |r,a| r << i } ] }.flatten } end |
#next_word ⇒ Object
18 19 20 21 22 23 |
# File 'lib/markov/generate.rb', line 18 def next_word word = current_word.match(/^,/) ? "," : current_word.split(",")[0] words = lookup(CGI.escape(word), @table) index = words[:probability].sample @word = CGI.unescape(words[:suffices][index]) end |
#text ⇒ Object
35 36 37 38 39 40 |
# File 'lib/markov/generate.rb', line 35 def text (0..@length).inject("#@start "){ |r,a| next_word r << "#{current_word.match(/^,/) ? "," : current_word.split(",")[0]} " }.strip.squeeze(" ").gsub(/\s(\.|\,|:|;|`|'|\?|!)/,"\\1") end |