-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathDictionary.rb
114 lines (103 loc) · 2.66 KB
/
Dictionary.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
class Dictionary
attr_accessor :name, :index_lang, :content_lang
def initialize
self.name = name
self.index_lang = index_lang
self.content_lang = content_lang
@cards = {}
end
def add(key, value, desc)
key.strip!
value.strip!
desc.strip!
if desc.empty?
$stderr.puts "ERROR: empty/missing dictionary description"
exit
end
(@cards[key] ||= Card.new(key)).add(value, desc)
end
def add_card(card)
if @cards[card.headword]
$stderr.puts "such card already exists: #{card.inspect}"
exit
else
@cards[card.headword] = card
end
end
def self.load_from_dsl(file)
d = Dictionary.new
if (file.gets =~ /^(?:\xEF\xBB\xBF)?#NAME\s*"(.*)"\s*$/)
d.name = $1
else
$stderr.puts "\#NAME is not the first line in the DSL file"
exit
end
if (file.gets =~ /^#INDEX_LANGUAGE\s*"(.*)"\s*$/)
d.index_lang = $1
else
$stderr.puts "\#INDEX_LANGUAGE is not the second line in the DSL file"
exit
end
if (file.gets =~ /^#CONTENTS_LANGUAGE\s*"(.*)"\s*$/)
d.content_lang = $1
else
$stderr.puts "\#CONTENTS_LANGUAGE is not the third line in the DSL file"
exit
end
card = nil
while (line = file.gets)
next if line.strip.empty?
line.rstrip!
if (line =~ /^(\S.*)$/) # headword
card = Card.new($1)
d.add_card(card)
elsif (line =~ /^\s/) # card body
card.parse_from_dsl(line)
else
$stderr.puts "Wrong line: #{line}"
exit
end
end
d
end
def check_valid
if name && index_lang && content_lang
# everything's fine
else
$stderr.puts "Required Dictionary Info is missing"
exit
end
end
def print_out(out_name)
check_valid
out = File.open(out_name, 'w')
# Dictionary Header
out.print "\xEF\xBB\xBF"
out.puts "\#NAME \"#{name}\""
out.puts "\#INDEX_LANGUAGE \"#{index_lang}\""
out.puts "\#CONTENTS_LANGUAGE \"#{content_lang}\""
@cards.values.sort.each { |card|
card.print_out(out)
}
out.close
$stderr.puts "File #{out_name} written...."
$stderr.puts "Total number of headwords: #{@cards.size}"
end
def each_card
@cards.values.sort.each { |card|
yield card
}
end
def get_txt_dicts
txt_dicts = {}
each_card { |card|
hwd = card.headword
card.entries.each { |trn, descs|
descs.each { |desc|
(txt_dicts[desc] ||= TxtDictionary.new(desc)).add(hwd, trn)
}
}
}
txt_dicts.values
end
end