Class: Libmarkov::Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/libmarkov.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(text) ⇒ Generator

Returns a new instance of Generator.



7
8
9
10
11
12
13
# File 'lib/libmarkov.rb', line 7

def initialize(text)
  @text = text
  @initKeys = []
  @dict = self.assembleDict
  # @keys = @dict.keys
  @max = 30
end

Instance Attribute Details

#dictObject

Returns the value of attribute dict.



5
6
7
# File 'lib/libmarkov.rb', line 5

def dict
  @dict
end

Instance Method Details

#assembleDictObject



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/libmarkov.rb', line 15

def assembleDict()
  dict = {}
  prefix = []

  @text.scan(/\S+/).each do |word|

    if prefix.length != 0 and prefix[0] != nil
      key = prefix.join(' ')
      dict[key] ||= []
      dict[key] << word

      if is_capital(key)
        @initKeys << key
      end
    end

    prefix[0] = prefix[1]
    prefix[1] = word
  end

  return dict
end

#generate(count = 10) ⇒ Object



63
64
65
66
67
68
69
70
# File 'lib/libmarkov.rb', line 63

def generate(count=10)
  sentences = []
  count.times do
    sentences << self.generate_sentence()
  end

  sentences.join(' ')
end

#generate_sentenceObject



50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/libmarkov.rb', line 50

def generate_sentence()
  sentence = [].concat(get_init_key.split(' '))

  @max.times do
    search = sentence.last(2).join(' ')
    val = @dict[search].sample
    sentence << val
    break if is_punctuated(val)
  end

  sentence.join(' ')
end

#get_init_keyObject



42
43
44
# File 'lib/libmarkov.rb', line 42

def get_init_key()
  @initKeys.sample
end

#is_capital(key) ⇒ Object



38
39
40
# File 'lib/libmarkov.rb', line 38

def is_capital(key)
  key[0] == key[0].upcase
end

#is_punctuated(key) ⇒ Object



46
47
48
# File 'lib/libmarkov.rb', line 46

def is_punctuated(key)
  key[/\.|\?|\!/] != nil
end