-
Notifications
You must be signed in to change notification settings - Fork 1
/
chain.rb
143 lines (109 loc) · 2.4 KB
/
chain.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
require "json"
module Treat
config_file = File.open('./config.json', 'r')
Config = JSON.load(config_file)
Config["delimiters"] = ["(",")",",",",",":","'",";"]
Config["unwanted_chars"] = ["\n", "-"]
def Treat.treat(text)
unwanted_chars = Config['unwanted_chars']
text = text.gsub(/[#{unwanted_chars.join}]{1}/,' ')
return text
end
def Treat.extract(text)
text = treat(text)
delimiters = Config['delimiters']
delim_regex = /(?<!\w)[#{delimiters.join}]{1}|[#{delimiters.join}](?=\W)/
statement_list = []
while delim_regex.match(text)
statement_list << $`
text = $'
prepend = $'
end
if prepend
statement_list << prepend
else
statement_list << text
end
statement_list = statement_list.keep_if { |statement|
/\w/ =~ statement
}
return statement_list
end
end
class Suffix < Hash
def initialize
super 0
@num_of_words = 0
end
def <<(word)
self[word] += 1
@num_of_words += 1
end
def spawn(select = :random)
case (select)
when :max then
max_val = self.values.max()
self.each_key { |word|
if self[word] == max_val
return word
end
}
when :random then
random_float = Random.rand
current = 0.0
accumulated = 0.0
self.each_key { |word|
num_of_times = self[word].to_f
accumulated += num_of_times/@num_of_words
if (current ... accumulated).include?(random_float)
return word
end
current = accumulated
}
end
end
def set_num_of_words()
total = 0
self.values.each { |x| total += x }
@num_of_words = total
end
end
class Chain < Hash
def initialize()
super {|hash,key| hash[key]=Suffix.new}
end
def Chain.build(text,level = 1)
statement_list = Treat.extract(text)
chain = Chain.new
count = 1
while count <= level
statement_list.each { |statement|
words = statement.split(' ')
chain["__BEGIN__"] << words[0]
words[0...-count].each_index do |index|
prefix = words[index,count].join(' ')
chain[prefix] << words[index+count]
end
}
count+=1
end
return chain
end
def Chain.load(file_name)
File.open(file_name) { |file|
text = file.read()
hash = JSON.parse(text)
chain = Chain.new
hash.each_key { |key|
suffix = Suffix.new
s_hash = hash[key]
s_hash.each_key { |s_key|
suffix[s_key] = s_hash[s_key]
}
suffix.set_num_of_words()
chain[key] = suffix
}
return chain
}
end
end