-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathwordnet.go
371 lines (333 loc) · 8.28 KB
/
wordnet.go
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
package wnram
import (
"fmt"
"os"
"path"
"path/filepath"
"strings"
"time"
)
// An initialized read-only, in-ram instance of the wordnet database.
// May safely be shared by multiple threads of execution
type Handle struct {
index map[string][]*cluster
db []*cluster
}
type index struct {
pos PartOfSpeech
lemma string
sense uint8
}
// The results of a search against the wordnet database
type Lookup struct {
word string // the word the user searched for
cluster *cluster // the discoverd synonym set
}
type syntacticRelation struct {
rel Relation
target *cluster
wordNumber uint8
}
type semanticRelation struct {
rel Relation
target *cluster
}
type word struct {
sense uint8
word string
relations []syntacticRelation
}
type cluster struct {
pos PartOfSpeech
words []word
gloss string
relations []semanticRelation
debug string
}
// Parts of speech
type PartOfSpeech uint8
// A set of multiple parts of speech
type PartOfSpeechList []PartOfSpeech
func (l PartOfSpeechList) Empty() bool {
return len(l) == 0
}
func (l PartOfSpeechList) Contains(want PartOfSpeech) bool {
for _, got := range l {
if got == want {
return true
}
}
return false
}
const (
Noun PartOfSpeech = iota
Verb
Adjective
// AdjectiveSatellite
Adverb
)
func (pos PartOfSpeech) String() string {
switch pos {
case Noun:
return "noun"
case Verb:
return "verb"
case Adjective:
return "adj"
case Adverb:
return "adv"
}
return "unknown"
}
// The ways in which synonym clusters may be related to others.
type Relation uint32
const (
AlsoSee Relation = 1 << iota
// A word with an opposite meaning
Antonym
// A noun for which adjectives express values.
// The noun weight is an attribute, for which the adjectives light and heavy express values.
Attribute
Cause
// Terms in different syntactic categories that have the same root form and are semantically related.
DerivationallyRelatedForm
// Adverbs are often derived from adjectives, and sometimes have antonyms; therefore the synset for an adverb usually contains a lexical pointer to the adjective from which it is derived.
DerivedFromAdjective
// A topical classification to which a synset has been linked with a REGION
InDomainRegion
InDomainTopic
InDomainUsage
ContainsDomainRegion
ContainsDomainTopic
ContainsDomainUsage
Entailment
// The generic term used to designate a whole class of specific instances.
// Y is a hypernym of X if X is a (kind of) Y .
Hypernym
InstanceHypernym
InstanceHyponym
// The specific term used to designate a member of a class. X is a hyponym of Y if X is a (kind of) Y .
Hyponym
MemberMeronym
PartMeronym
SubstanceMeronym
MemberHolonym
PartHolonym
SubstanceHolonym
ParticipleOfVerb
RelatedForm
SimilarTo
VerbGroup
)
const Pertainym = DerivedFromAdjective
func (w *Lookup) String() string {
return fmt.Sprintf("%q (%s)", w.word, w.cluster.pos.String())
}
// The specific word that was found
func (w *Lookup) Word() string {
return w.word
}
// A canonical synonym for this word
func (w *Lookup) Lemma() string {
return w.cluster.words[0].word
}
// A description of this meaning
func (w *Lookup) Gloss() string {
return w.cluster.gloss
}
func (w *Lookup) DumpStr() string {
s := fmt.Sprintf("Word: %s\n", w.String())
s += fmt.Sprintf("Synonyms: ")
words := []string{}
for _, w := range w.cluster.words {
words = append(words, w.word)
}
s += strings.Join(words, ", ") + "\n"
s += fmt.Sprintf("%d semantic relationships\n", len(w.cluster.relations))
s += "| " + w.cluster.gloss + "\n"
return s
}
func (w *Lookup) Dump() {
fmt.Printf("%s", w.DumpStr())
}
func (w *Lookup) POS() PartOfSpeech {
return w.cluster.pos
}
func (w *Lookup) Synonyms() (synonyms []string) {
for _, w := range w.cluster.words {
synonyms = append(synonyms, w.word)
}
return synonyms
}
// Get words related to this word. r is a bitfield of relation types
// to include
func (w *Lookup) Related(r Relation) (relationships []Lookup) {
// first look for semantic relationships
for _, rel := range w.cluster.relations {
if rel.rel&r != Relation(0) {
relationships = append(relationships, Lookup{
word: rel.target.words[0].word,
cluster: rel.target,
})
}
}
// next let's look for syntactic relationships
key := normalize(w.word)
for _, word := range w.cluster.words {
if key == word.word {
for _, rel := range word.relations {
if rel.rel&r != Relation(0) {
relationships = append(relationships, Lookup{
word: rel.target.words[rel.wordNumber].word,
cluster: rel.target,
})
}
}
}
}
return relationships
}
// Initialize a new in-ram WordNet databases reading files from the
// specified directory.
func New(dir string) (*Handle, error) {
cnt := 0
type ix struct {
index string
pos PartOfSpeech
}
byOffset := map[ix]*cluster{}
err := filepath.Walk(dir, func(filename string, info os.FileInfo, err error) error {
start := time.Now()
if err != nil || info.IsDir() {
return err
}
// Skip '^.', '~$', and non-files.
if strings.HasPrefix(path.Base(filename), ".") || strings.HasSuffix(filename, "~") || strings.HasSuffix(filename, "#") {
return nil
}
// read only data files
if !strings.HasPrefix(path.Base(filename), "data") {
return nil
}
err = inPlaceReadLineFromPath(filename, func(data []byte, line, offset int64) error {
cnt++
if p, err := parseLine(data, line, offset); err != nil {
return fmt.Errorf("%s:%d: %s", err)
} else if p != nil {
// first, let's identify the cluster
index := ix{p.byteOffset, p.pos}
c, ok := byOffset[index]
if !ok {
c = &cluster{}
byOffset[index] = c
}
// now update
c.pos = p.pos
c.words = p.words
c.gloss = p.gloss
c.debug = p.byteOffset
// now let's build relations
for _, r := range p.rels {
rindex := ix{r.offset, r.pos}
rcluster, ok := byOffset[rindex]
if !ok {
// create the other side of the relationship
rcluster = &cluster{}
byOffset[rindex] = rcluster
}
if r.isSemantic {
c.relations = append(c.relations, semanticRelation{
rel: r.rel,
target: rcluster,
})
} else {
if int(r.source) >= len(c.words) {
return fmt.Errorf("%s:%d: error parsing relations, bogus source (words: %d, offset: %d) [%s]", filename, line, r.source, len(c.words), string(data))
}
c.words[r.source].relations = append(c.words[r.source].relations, syntacticRelation{
rel: r.rel,
target: rcluster,
wordNumber: r.dest,
})
}
}
}
return nil
})
fmt.Printf("%s in %s\n", filename, time.Since(start).String())
return err
})
if err != nil {
return nil, err
}
// now that we've built up the in ram database, lets' index it
h := Handle{
db: make([]*cluster, 0, len(byOffset)),
index: make(map[string][]*cluster),
}
for _, c := range byOffset {
if len(c.words) == 0 {
return nil, fmt.Errorf("ERROR, internal consistency error -> cluster without words %v\n", c)
}
// add to the global slice of synsets (supports iteration)
h.db = append(h.db, c)
// now index all the strings
for _, w := range c.words {
key := normalize(w.word)
v, _ := h.index[key]
v = append(v, c)
h.index[key] = v
}
}
return &h, nil
}
type Criteria struct {
Matching string
POS PartOfSpeechList
}
func normalize(in string) string {
return strings.ToLower(strings.Join(strings.Fields(in), " "))
}
// look up word clusters based on given criteria
func (h *Handle) Lookup(crit Criteria) ([]Lookup, error) {
if crit.Matching == "" {
return nil, fmt.Errorf("empty string passed as criteria to lookup")
}
searchStr := normalize(crit.Matching)
clusters, _ := h.index[searchStr]
found := []Lookup{}
for _, c := range clusters {
if len(crit.POS) > 0 {
satisfied := false
for _, p := range crit.POS {
if p == c.pos {
satisfied = true
break
}
}
if !satisfied {
continue
}
}
found = append(found, Lookup{
word: crit.Matching,
cluster: c,
})
}
return found, nil
}
func (h *Handle) Iterate(pos PartOfSpeechList, cb func(Lookup) error) error {
for _, c := range h.db {
if !pos.Empty() && !pos.Contains(c.pos) {
continue
}
err := cb(Lookup{
word: c.words[0].word,
cluster: c,
})
if err != nil {
return err
}
}
return nil
}