-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path2gram_word_table.rb
More file actions
43 lines (37 loc) · 935 Bytes
/
Copy path2gram_word_table.rb
File metadata and controls
43 lines (37 loc) · 935 Bytes
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
class WordTable
def initialize(filename=nil)
@table = Hash.new
add_file_to_table(filename) if !!filename
end
def add_file_to_table(filename)
doc = parse_file(filename)
@table["."] ||= []
@table["."] << doc[0]
doc.each_index do |word_i|
break if word_i == (doc.length-1)
@table[doc[word_i]] ||= []
@table[doc[word_i]] << doc[word_i+1]
end
end
def generate_text
text = @table["."].sample
text += text_loop(text)
puts text.gsub(/\s+([.,!?])/, '\1')
end
private
def parse_file(filename)
File.readlines(filename).join.gsub(/([.,!?])/, ' \1').split(/\s+/)
end
def text_loop(curr_word)
next_word = @table[curr_word].sample
text = " #{next_word}"
if [".", "?", "!"].include?(next_word) && should_stop?
text
else
text + text_loop(next_word)
end
end
def should_stop?
rand < 0.6
end
end