Class: Markov::Dictionary

Inherits:
Object
  • Object
show all
Includes:
Util
Defined in:
lib/markov/dictionary.rb

Instance Method Summary collapse

Methods included from Util

#random_number, #tokens_to_debug, #tokens_to_sentence, #tokens_to_words

Constructor Details

#initialize(depth) ⇒ Dictionary

Returns a new instance of Dictionary.



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

def initialize(depth)
  @depth = depth
  
  @dictionary = {}
  @start_words = {}
  
  srand
end

Instance Method Details

#add_to_dictionary(tokens) ⇒ Object



47
48
49
50
51
52
53
54
55
# File 'lib/markov/dictionary.rb', line 47

def add_to_dictionary(tokens)
  token = tokens.last
  return if token == nil || token.word == ""
  
  key_words = tokens_to_words tokens[0, @depth-1]     
  
  @dictionary[key_words] ||= []
  @dictionary[key_words] << token
end

#add_to_start_words(tokens) ⇒ Object



38
39
40
41
42
43
44
45
# File 'lib/markov/dictionary.rb', line 38

def add_to_start_words(tokens)
  return if tokens[0].kind != :word
  
  tokens[0].word = tokens[0].word.capitalize
  start_words = tokens_to_words tokens
  
  @start_words[start_words] ||= tokens
end

#dump_dictionaryObject



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/markov/dictionary.rb', line 26

def dump_dictionary
  @dictionary.keys.each do |keys|
    following = @dictionary[keys]
    sentence = []
    following.each do |word|
      sentence << "#{word.to_s},"
    end
    s = sentence.join(" ")
    puts "#{keys} => #{s.slice(0,s.length-1)}"
  end
end

#dump_startwordsObject



20
21
22
23
24
# File 'lib/markov/dictionary.rb', line 20

def dump_startwords
  @start_words.keys.each do |start_words|
    puts "#{start_words} -> #{tokens_to_sentence @dictionary[start_words]}"
  end
end

#empty?Boolean

Returns:

  • (Boolean)


16
17
18
# File 'lib/markov/dictionary.rb', line 16

def empty?
  @dictionary.empty?
end

#select_next_token(tokens) ⇒ Object



61
62
63
64
65
66
# File 'lib/markov/dictionary.rb', line 61

def select_next_token(tokens)
  token = @dictionary[ tokens_to_words(tokens)]
  
  return Markov::Token.new("X", :noop) if token == nil  
  token[random_number(tokens.length-1)]
end

#select_next_word(tokens) ⇒ Object



68
69
70
71
72
73
74
# File 'lib/markov/dictionary.rb', line 68

def select_next_word(tokens)
  token = nil
  begin
    token = select_next_token(tokens)
  end until token.kind == :word
  token
end

#select_start_wordsObject



57
58
59
# File 'lib/markov/dictionary.rb', line 57

def select_start_words
  @start_words[ @start_words.keys[random_number( @start_words.keys.length-1)]]
end