CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-natural

Comprehensive natural language processing library with tokenization, stemming, classification, sentiment analysis, phonetics, distance algorithms, and WordNet integration.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

wordnet.mddocs/

WordNet

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.

Capabilities

WordNet Interface

Main interface for querying the WordNet lexical database.

/**
 * WordNet lexical database interface
 * @param dataDir - Optional path to WordNet data directory
 */
class WordNet {
  constructor(dataDir?: string);
  
  /**
   * Look up word definitions and relationships
   * @param word - Word to look up
   * @param callback - Callback receiving array of results
   */
  lookup(word: string, callback: (results: WordNetResult[]) => void): void;
  
  /**
   * Get synset by offset and part of speech
   * @param synsetOffset - Numerical synset offset
   * @param pos - Part of speech ('n', 'v', 'a', 's', 'r')
   * @param callback - Callback receiving synset result
   */
  get(synsetOffset: number, pos: string, callback: (result: WordNetResult) => void): void;
  
  /**
   * Get synonyms for a synset
   * @param synsetOffset - Synset offset
   * @param pos - Part of speech
   * @param callback - Callback receiving synonyms array
   */
  getSynonyms(synsetOffset: number, pos: string, callback: (synonyms: string[]) => void): void;
  
  /**
   * Look up synonyms for a word
   * @param word - Word to find synonyms for
   * @param callback - Callback receiving synonyms array
   */
  lookupSynonyms(word: string, callback: (synonyms: string[]) => void): void;
}

/**
 * WordNet result object
 */
interface WordNetResult {
  synsetOffset: number;
  pos: string;
  gloss: string;
  words: string[];
  synonyms: string[];
  definition: string;
}

Part of Speech Codes:

  • 'n' - Noun
  • 'v' - Verb
  • 'a' - Adjective
  • 's' - Adjective satellite
  • 'r' - Adverb

Usage Examples:

const natural = require('natural');

// Create WordNet instance
const wordnet = new natural.WordNet();

// Look up word definitions
wordnet.lookup('dog', (results) => {
  console.log('Definitions for "dog":');
  results.forEach((result, i) => {
    console.log(`${i + 1}. [${result.pos}] ${result.gloss}`);
    console.log(`   Synonyms: ${result.synonyms.join(', ')}`);
  });
});

// Look up synonyms directly
wordnet.lookupSynonyms('happy', (synonyms) => {
  console.log('Synonyms for "happy":', synonyms);
});

// Get specific synset
wordnet.get(2084071, 'n', (result) => {
  console.log('Synset 2084071 (noun):', result);
});

// Get synonyms for specific synset
wordnet.getSynonyms(2084071, 'n', (synonyms) => {
  console.log('Synonyms for synset 2084071:', synonyms);
});

Advanced WordNet Usage

Finding semantic relationships:

const natural = require('natural');

/**
 * Find semantic relationships between words
 */
function findSemanticRelationships(word1, word2, callback) {
  const wordnet = new natural.WordNet();
  const results = {
    word1Senses: [],
    word2Senses: [],
    commonSynonyms: [],
    relatedSenses: []
  };
  
  // Look up both words
  wordnet.lookup(word1, (results1) => {
    results.word1Senses = results1;
    
    wordnet.lookup(word2, (results2) => {
      results.word2Senses = results2;
      
      // Find common synonyms
      const synonyms1 = new Set();
      const synonyms2 = new Set();
      
      results1.forEach(sense => {
        sense.synonyms.forEach(syn => synonyms1.add(syn));
      });
      
      results2.forEach(sense => {
        sense.synonyms.forEach(syn => synonyms2.add(syn));
      });
      
      results.commonSynonyms = [...synonyms1].filter(syn => synonyms2.has(syn));
      
      callback(results);
    });
  });
}

// Usage
findSemanticRelationships('happy', 'joyful', (relationships) => {
  console.log('Semantic relationships:');
  console.log('Common synonyms:', relationships.commonSynonyms);
  console.log(`${relationships.word1Senses.length} senses for first word`);
  console.log(`${relationships.word2Senses.length} senses for second word`);
});

Word sense disambiguation:

const natural = require('natural');

/**
 * Disambiguate word senses based on context
 */
function disambiguateWordSense(word, context, callback) {
  const wordnet = new natural.WordNet();
  
  wordnet.lookup(word, (senses) => {
    if (senses.length === 0) {
      callback(null);
      return;
    }
    
    if (senses.length === 1) {
      callback(senses[0]);
      return;
    }
    
    // Score each sense based on context overlap
    const contextWords = new Set(
      natural.WordTokenizer.tokenize(context.toLowerCase())
        .filter(w => w.length > 2)
    );
    
    const scoredSenses = senses.map(sense => {
      const glossWords = new Set(
        natural.WordTokenizer.tokenize(sense.gloss.toLowerCase())
          .filter(w => w.length > 2)
      );
      
      // Calculate overlap score
      const overlap = [...contextWords].filter(w => glossWords.has(w)).length;
      const score = overlap / Math.max(contextWords.size, glossWords.size);
      
      return { sense, score };
    });
    
    // Return highest scoring sense
    const bestSense = scoredSenses.reduce((best, current) => 
      current.score > best.score ? current : best
    );
    
    callback(bestSense.sense);
  });
}

// Usage
const context = "The bank of the river was muddy and steep";
disambiguateWordSense('bank', context, (bestSense) => {
  if (bestSense) {
    console.log('Best sense for "bank" in context:');
    console.log(`[${bestSense.pos}] ${bestSense.gloss}`);
  }
});

Vocabulary enrichment:

const natural = require('natural');

/**
 * Enrich vocabulary by finding related words
 */
function enrichVocabulary(seedWords, callback) {
  const wordnet = new natural.WordNet();
  const enrichedWords = new Set(seedWords);
  let processed = 0;
  
  seedWords.forEach(word => {
    wordnet.lookupSynonyms(word, (synonyms) => {
      synonyms.forEach(synonym => enrichedWords.add(synonym));
      
      processed++;
      if (processed === seedWords.length) {
        callback([...enrichedWords]);
      }
    });
  });
}

// Usage
const seedWords = ['happy', 'joyful', 'content'];
enrichVocabulary(seedWords, (enriched) => {
  console.log('Original words:', seedWords);
  console.log('Enriched vocabulary:', enriched);
  console.log(`Expanded from ${seedWords.length} to ${enriched.length} words`);
});

Thesaurus functionality:

const natural = require('natural');

/**
 * Create thesaurus entries for words
 */
class ThesaurusBuilder {
  constructor() {
    this.wordnet = new natural.WordNet();
  }
  
  /**
   * Build thesaurus entry for a word
   * @param word - Word to build entry for
   * @param callback - Callback with thesaurus entry
   */
  buildEntry(word, callback) {
    this.wordnet.lookup(word, (senses) => {
      const entry = {
        word: word,
        definitions: [],
        synonyms: new Set(),
        antonyms: new Set() // Note: WordNet antonym support would need additional implementation
      };
      
      senses.forEach(sense => {
        entry.definitions.push({
          pos: sense.pos,
          definition: sense.gloss,
          examples: [] // Would be extracted from gloss if available
        });
        
        sense.synonyms.forEach(syn => {
          if (syn !== word) entry.synonyms.add(syn);
        });
      });
      
      callback({
        ...entry,
        synonyms: [...entry.synonyms],
        antonyms: [...entry.antonyms]
      });
    });
  }
  
  /**
   * Build entries for multiple words
   * @param words - Array of words
   * @param callback - Callback with all entries
   */
  buildEntries(words, callback) {
    const entries = {};
    let processed = 0;
    
    words.forEach(word => {
      this.buildEntry(word, (entry) => {
        entries[word] = entry;
        processed++;
        
        if (processed === words.length) {
          callback(entries);
        }
      });
    });
  }
}

// Usage
const thesaurus = new ThesaurusBuilder();

thesaurus.buildEntry('run', (entry) => {
  console.log(`Thesaurus entry for "${entry.word}":`);
  console.log('Definitions:');
  entry.definitions.forEach((def, i) => {
    console.log(`  ${i + 1}. [${def.pos}] ${def.definition}`);
  });
  console.log('Synonyms:', entry.synonyms.join(', '));
});

// Build multiple entries
const wordsToProcess = ['walk', 'run', 'jump'];
thesaurus.buildEntries(wordsToProcess, (entries) => {
  Object.values(entries).forEach(entry => {
    console.log(`\n${entry.word}: ${entry.synonyms.slice(0, 5).join(', ')}...`);
  });
});

Semantic Search

const natural = require('natural');

/**
 * Semantic search using WordNet
 */
class SemanticSearcher {
  constructor() {
    this.wordnet = new natural.WordNet();
  }
  
  /**
   * Find semantically similar words
   * @param query - Query word
   * @param candidates - Array of candidate words
   * @param callback - Callback with ranked results
   */
  search(query, candidates, callback) {
    this.wordnet.lookup(query, (querySenses) => {
      if (querySenses.length === 0) {
        callback([]);
        return;
      }
      
      const queryTerms = new Set();
      querySenses.forEach(sense => {
        natural.WordTokenizer.tokenize(sense.gloss.toLowerCase())
          .forEach(term => queryTerms.add(term));
        sense.synonyms.forEach(syn => queryTerms.add(syn.toLowerCase()));
      });
      
      const results = [];
      let processed = 0;
      
      candidates.forEach(candidate => {
        this.wordnet.lookup(candidate, (candidateSenses) => {
          let maxScore = 0;
          
          candidateSenses.forEach(sense => {
            const candidateTerms = new Set();
            natural.WordTokenizer.tokenize(sense.gloss.toLowerCase())
              .forEach(term => candidateTerms.add(term));
            sense.synonyms.forEach(syn => candidateTerms.add(syn.toLowerCase()));
            
            // Calculate Jaccard similarity
            const intersection = [...queryTerms].filter(term => candidateTerms.has(term)).length;
            const union = new Set([...queryTerms, ...candidateTerms]).size;
            const score = intersection / union;
            
            maxScore = Math.max(maxScore, score);
          });
          
          results.push({ word: candidate, score: maxScore });
          processed++;
          
          if (processed === candidates.length) {
            results.sort((a, b) => b.score - a.score);
            callback(results);
          }
        });
      });
    });
  }
}

// Usage
const searcher = new SemanticSearcher();
const query = 'automobile';
const candidates = ['car', 'truck', 'bicycle', 'house', 'tree', 'vehicle'];

searcher.search(query, candidates, (results) => {
  console.log(`Semantic search results for "${query}":`);
  results.forEach((result, i) => {
    console.log(`${i + 1}. ${result.word} (score: ${result.score.toFixed(3)})`);
  });
});

docs

classification.md

distance.md

index.md

ngrams-tfidf.md

phonetics.md

pos-tagging.md

sentiment.md

text-processing.md

transliterators.md

utilities.md

wordnet.md

tile.json