class Ruffini::Markov
This class provides a markov chain text generator.
Public Class Methods
new(depth = 2, filename = nil)
click to toggle source
Creates a new markov text generator with a given depth
.
If no depth
is provided, the constructor defaults to a depth of 2.
If a filename
is provided, the constructor reads the dictionary from a file.
# File lib/ruffini.rb, line 17 def initialize(depth = 2, filename = nil) @DEPTH = depth if filename.nil? @store = {} else @store = Marshal.load(Zlib::Inflate.inflate(File.read(filename))) end end
Public Instance Methods
generate(count, start = nil)
click to toggle source
Generates count
words using the dictionary, optionally starting from the last n words of start
, if start
is provided (accepts Array or String).
# File lib/ruffini.rb, line 49 def generate(count, start = nil) output = [] if !start.nil? if start.class == String key = start.downcase.split.last(@DEPTH) else key = start.last(@DEPTH) end else key = @store.keys.shuffle.first end key.map { |word| output.push word } count.times { if @store[key].nil? else word = @store[key].shuffle.first output.push word key = key.last(@DEPTH - 1).push word end } output.join(" ") end
parse!(string)
click to toggle source
Parses a given string
and adds its words to the markov dictionary.
# File lib/ruffini.rb, line 28 def parse!(string) words = string.split.map(&:downcase) for index in 0 .. (words.length - (@DEPTH + 1)) if @store[ words[index..index+(@DEPTH - 1)] ].nil? @store[ words[index..index+(@DEPTH - 1)] ] = [words[index+@DEPTH]] else @store[ words[index..index+(@DEPTH - 1)] ].push words[index+@DEPTH] end end return @store end
parse_file!(filename)
click to toggle source
Convenience method to parse an entire file by filename
.
# File lib/ruffini.rb, line 42 def parse_file!(filename) self.parse!(File.read(filename)) end
save!(filename)
click to toggle source
Serializes and compresses the markov dictionary to filename
. The file is stored as a zlib-compressed, marshalled Hash.
# File lib/ruffini.rb, line 79 def save!(filename) File.write(filename, Zlib::Deflate.deflate(Marshal.dump(@store))) end