or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

classification.mddistance.mdindex.mdngrams-tfidf.mdphonetics.mdpos-tagging.mdsentiment.mdtext-processing.mdtransliterators.mdutilities.mdwordnet.md

wordnet.mddocs/

0

# WordNet

1

2

Interface to WordNet lexical database for accessing word definitions, synonyms, and semantic relationships. WordNet is a large lexical database of English organized as a semantic network.

3

4

## Capabilities

5

6

### WordNet Interface

7

8

Main interface for querying the WordNet lexical database.

9

10

```javascript { .api }

11

/**

12

* WordNet lexical database interface

13

* @param dataDir - Optional path to WordNet data directory

14

*/

15

class WordNet {

16

constructor(dataDir?: string);

17

18

/**

19

* Look up word definitions and relationships

20

* @param word - Word to look up

21

* @param callback - Callback receiving array of results

22

*/

23

lookup(word: string, callback: (results: WordNetResult[]) => void): void;

24

25

/**

26

* Get synset by offset and part of speech

27

* @param synsetOffset - Numerical synset offset

28

* @param pos - Part of speech ('n', 'v', 'a', 's', 'r')

29

* @param callback - Callback receiving synset result

30

*/

31

get(synsetOffset: number, pos: string, callback: (result: WordNetResult) => void): void;

32

33

/**

34

* Get synonyms for a synset

35

* @param synsetOffset - Synset offset

36

* @param pos - Part of speech

37

* @param callback - Callback receiving synonyms array

38

*/

39

getSynonyms(synsetOffset: number, pos: string, callback: (synonyms: string[]) => void): void;

40

41

/**

42

* Look up synonyms for a word

43

* @param word - Word to find synonyms for

44

* @param callback - Callback receiving synonyms array

45

*/

46

lookupSynonyms(word: string, callback: (synonyms: string[]) => void): void;

47

}

48

49

/**

50

* WordNet result object

51

*/

52

interface WordNetResult {

53

synsetOffset: number;

54

pos: string;

55

gloss: string;

56

words: string[];

57

synonyms: string[];

58

definition: string;

59

}

60

```

61

62

**Part of Speech Codes:**

63

- `'n'` - Noun

64

- `'v'` - Verb

65

- `'a'` - Adjective

66

- `'s'` - Adjective satellite

67

- `'r'` - Adverb

68

69

**Usage Examples:**

70

71

```javascript

72

const natural = require('natural');

73

74

// Create WordNet instance

75

const wordnet = new natural.WordNet();

76

77

// Look up word definitions

78

wordnet.lookup('dog', (results) => {

79

console.log('Definitions for "dog":');

80

results.forEach((result, i) => {

81

console.log(`${i + 1}. [${result.pos}] ${result.gloss}`);

82

console.log(` Synonyms: ${result.synonyms.join(', ')}`);

83

});

84

});

85

86

// Look up synonyms directly

87

wordnet.lookupSynonyms('happy', (synonyms) => {

88

console.log('Synonyms for "happy":', synonyms);

89

});

90

91

// Get specific synset

92

wordnet.get(2084071, 'n', (result) => {

93

console.log('Synset 2084071 (noun):', result);

94

});

95

96

// Get synonyms for specific synset

97

wordnet.getSynonyms(2084071, 'n', (synonyms) => {

98

console.log('Synonyms for synset 2084071:', synonyms);

99

});

100

```

101

102

### Advanced WordNet Usage

103

104

**Finding semantic relationships:**

105

106

```javascript

107

const natural = require('natural');

108

109

/**

110

* Find semantic relationships between words

111

*/

112

function findSemanticRelationships(word1, word2, callback) {

113

const wordnet = new natural.WordNet();

114

const results = {

115

word1Senses: [],

116

word2Senses: [],

117

commonSynonyms: [],

118

relatedSenses: []

119

};

120

121

// Look up both words

122

wordnet.lookup(word1, (results1) => {

123

results.word1Senses = results1;

124

125

wordnet.lookup(word2, (results2) => {

126

results.word2Senses = results2;

127

128

// Find common synonyms

129

const synonyms1 = new Set();

130

const synonyms2 = new Set();

131

132

results1.forEach(sense => {

133

sense.synonyms.forEach(syn => synonyms1.add(syn));

134

});

135

136

results2.forEach(sense => {

137

sense.synonyms.forEach(syn => synonyms2.add(syn));

138

});

139

140

results.commonSynonyms = [...synonyms1].filter(syn => synonyms2.has(syn));

141

142

callback(results);

143

});

144

});

145

}

146

147

// Usage

148

findSemanticRelationships('happy', 'joyful', (relationships) => {

149

console.log('Semantic relationships:');

150

console.log('Common synonyms:', relationships.commonSynonyms);

151

console.log(`${relationships.word1Senses.length} senses for first word`);

152

console.log(`${relationships.word2Senses.length} senses for second word`);

153

});

154

```

155

156

**Word sense disambiguation:**

157

158

```javascript

159

const natural = require('natural');

160

161

/**

162

* Disambiguate word senses based on context

163

*/

164

function disambiguateWordSense(word, context, callback) {

165

const wordnet = new natural.WordNet();

166

167

wordnet.lookup(word, (senses) => {

168

if (senses.length === 0) {

169

callback(null);

170

return;

171

}

172

173

if (senses.length === 1) {

174

callback(senses[0]);

175

return;

176

}

177

178

// Score each sense based on context overlap

179

const contextWords = new Set(

180

natural.WordTokenizer.tokenize(context.toLowerCase())

181

.filter(w => w.length > 2)

182

);

183

184

const scoredSenses = senses.map(sense => {

185

const glossWords = new Set(

186

natural.WordTokenizer.tokenize(sense.gloss.toLowerCase())

187

.filter(w => w.length > 2)

188

);

189

190

// Calculate overlap score

191

const overlap = [...contextWords].filter(w => glossWords.has(w)).length;

192

const score = overlap / Math.max(contextWords.size, glossWords.size);

193

194

return { sense, score };

195

});

196

197

// Return highest scoring sense

198

const bestSense = scoredSenses.reduce((best, current) =>

199

current.score > best.score ? current : best

200

);

201

202

callback(bestSense.sense);

203

});

204

}

205

206

// Usage

207

const context = "The bank of the river was muddy and steep";

208

disambiguateWordSense('bank', context, (bestSense) => {

209

if (bestSense) {

210

console.log('Best sense for "bank" in context:');

211

console.log(`[${bestSense.pos}] ${bestSense.gloss}`);

212

}

213

});

214

```

215

216

**Vocabulary enrichment:**

217

218

```javascript

219

const natural = require('natural');

220

221

/**

222

* Enrich vocabulary by finding related words

223

*/

224

function enrichVocabulary(seedWords, callback) {

225

const wordnet = new natural.WordNet();

226

const enrichedWords = new Set(seedWords);

227

let processed = 0;

228

229

seedWords.forEach(word => {

230

wordnet.lookupSynonyms(word, (synonyms) => {

231

synonyms.forEach(synonym => enrichedWords.add(synonym));

232

233

processed++;

234

if (processed === seedWords.length) {

235

callback([...enrichedWords]);

236

}

237

});

238

});

239

}

240

241

// Usage

242

const seedWords = ['happy', 'joyful', 'content'];

243

enrichVocabulary(seedWords, (enriched) => {

244

console.log('Original words:', seedWords);

245

console.log('Enriched vocabulary:', enriched);

246

console.log(`Expanded from ${seedWords.length} to ${enriched.length} words`);

247

});

248

```

249

250

**Thesaurus functionality:**

251

252

```javascript

253

const natural = require('natural');

254

255

/**

256

* Create thesaurus entries for words

257

*/

258

class ThesaurusBuilder {

259

constructor() {

260

this.wordnet = new natural.WordNet();

261

}

262

263

/**

264

* Build thesaurus entry for a word

265

* @param word - Word to build entry for

266

* @param callback - Callback with thesaurus entry

267

*/

268

buildEntry(word, callback) {

269

this.wordnet.lookup(word, (senses) => {

270

const entry = {

271

word: word,

272

definitions: [],

273

synonyms: new Set(),

274

antonyms: new Set() // Note: WordNet antonym support would need additional implementation

275

};

276

277

senses.forEach(sense => {

278

entry.definitions.push({

279

pos: sense.pos,

280

definition: sense.gloss,

281

examples: [] // Would be extracted from gloss if available

282

});

283

284

sense.synonyms.forEach(syn => {

285

if (syn !== word) entry.synonyms.add(syn);

286

});

287

});

288

289

callback({

290

...entry,

291

synonyms: [...entry.synonyms],

292

antonyms: [...entry.antonyms]

293

});

294

});

295

}

296

297

/**

298

* Build entries for multiple words

299

* @param words - Array of words

300

* @param callback - Callback with all entries

301

*/

302

buildEntries(words, callback) {

303

const entries = {};

304

let processed = 0;

305

306

words.forEach(word => {

307

this.buildEntry(word, (entry) => {

308

entries[word] = entry;

309

processed++;

310

311

if (processed === words.length) {

312

callback(entries);

313

}

314

});

315

});

316

}

317

}

318

319

// Usage

320

const thesaurus = new ThesaurusBuilder();

321

322

thesaurus.buildEntry('run', (entry) => {

323

console.log(`Thesaurus entry for "${entry.word}":`);

324

console.log('Definitions:');

325

entry.definitions.forEach((def, i) => {

326

console.log(` ${i + 1}. [${def.pos}] ${def.definition}`);

327

});

328

console.log('Synonyms:', entry.synonyms.join(', '));

329

});

330

331

// Build multiple entries

332

const wordsToProcess = ['walk', 'run', 'jump'];

333

thesaurus.buildEntries(wordsToProcess, (entries) => {

334

Object.values(entries).forEach(entry => {

335

console.log(`\n${entry.word}: ${entry.synonyms.slice(0, 5).join(', ')}...`);

336

});

337

});

338

```

339

340

### Semantic Search

341

342

```javascript

343

const natural = require('natural');

344

345

/**

346

* Semantic search using WordNet

347

*/

348

class SemanticSearcher {

349

constructor() {

350

this.wordnet = new natural.WordNet();

351

}

352

353

/**

354

* Find semantically similar words

355

* @param query - Query word

356

* @param candidates - Array of candidate words

357

* @param callback - Callback with ranked results

358

*/

359

search(query, candidates, callback) {

360

this.wordnet.lookup(query, (querySenses) => {

361

if (querySenses.length === 0) {

362

callback([]);

363

return;

364

}

365

366

const queryTerms = new Set();

367

querySenses.forEach(sense => {

368

natural.WordTokenizer.tokenize(sense.gloss.toLowerCase())

369

.forEach(term => queryTerms.add(term));

370

sense.synonyms.forEach(syn => queryTerms.add(syn.toLowerCase()));

371

});

372

373

const results = [];

374

let processed = 0;

375

376

candidates.forEach(candidate => {

377

this.wordnet.lookup(candidate, (candidateSenses) => {

378

let maxScore = 0;

379

380

candidateSenses.forEach(sense => {

381

const candidateTerms = new Set();

382

natural.WordTokenizer.tokenize(sense.gloss.toLowerCase())

383

.forEach(term => candidateTerms.add(term));

384

sense.synonyms.forEach(syn => candidateTerms.add(syn.toLowerCase()));

385

386

// Calculate Jaccard similarity

387

const intersection = [...queryTerms].filter(term => candidateTerms.has(term)).length;

388

const union = new Set([...queryTerms, ...candidateTerms]).size;

389

const score = intersection / union;

390

391

maxScore = Math.max(maxScore, score);

392

});

393

394

results.push({ word: candidate, score: maxScore });

395

processed++;

396

397

if (processed === candidates.length) {

398

results.sort((a, b) => b.score - a.score);

399

callback(results);

400

}

401

});

402

});

403

});

404

}

405

}

406

407

// Usage

408

const searcher = new SemanticSearcher();

409

const query = 'automobile';

410

const candidates = ['car', 'truck', 'bicycle', 'house', 'tree', 'vehicle'];

411

412

searcher.search(query, candidates, (results) => {

413

console.log(`Semantic search results for "${query}":`);

414

results.forEach((result, i) => {

415

console.log(`${i + 1}. ${result.word} (score: ${result.score.toFixed(3)})`);

416

});

417

});

418

```