Comprehensive natural language processing library with tokenization, stemming, classification, sentiment analysis, phonetics, distance algorithms, and WordNet integration.
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Multi-language sentiment analysis using various lexicons and methodologies for determining emotional tone in text. Natural supports multiple sentiment analysis approaches across different languages.
Main sentiment analysis class supporting multiple languages and sentiment lexicons.
/**
* Sentiment analyzer with multi-language and multi-lexicon support
* @param language - Target language for analysis
* @param stemmer - Optional stemmer for word preprocessing
* @param type - Sentiment lexicon type to use
*/
class SentimentAnalyzer {
constructor(language: string, stemmer?: object, type: string);
/**
* Calculate sentiment score for an array of words
* @param words - Array of word strings (usually tokens)
* @returns Sentiment score (typically negative to positive range)
*/
getSentiment(words: string[]): number;
}Languages:
'English' - English sentiment analysis'Spanish' - Spanish sentiment analysis'Portuguese' - Portuguese sentiment analysis'Dutch' - Dutch sentiment analysis'Italian' - Italian sentiment analysis'French' - French sentiment analysis'German' - German sentiment analysis'Galician' - Galician sentiment analysis'Catalan' - Catalan sentiment analysis'Basque' - Basque sentiment analysisSentiment Types:
'afinn' - AFINN lexicon (English, Spanish, Portuguese)'afinnFinancialMarketNews' - AFINN for financial market news (English)'senticon' - SentiCon lexicon (Spanish, English, Galician, Catalan, Basque)'pattern' - Pattern lexicon (Dutch, Italian, English, French, German)Usage Examples:
const natural = require('natural');
// English AFINN sentiment analysis
const analyzer = new natural.SentimentAnalyzer('English', natural.PorterStemmer, 'afinn');
// Tokenize and analyze
const tokens = natural.WordTokenizer.tokenize('I love this amazing product');
const score = analyzer.getSentiment(tokens);
console.log(score); // Positive score
// Negative sentiment
const negativeTokens = natural.WordTokenizer.tokenize('This is terrible and awful');
const negativeScore = analyzer.getSentiment(negativeTokens);
console.log(negativeScore); // Negative score
// Spanish sentiment analysis
const spanishAnalyzer = new natural.SentimentAnalyzer('Spanish', null, 'afinn');
const spanishTokens = ['me', 'gusta', 'mucho', 'este', 'producto'];
const spanishScore = spanishAnalyzer.getSentiment(spanishTokens);
console.log(spanishScore);
// Financial market sentiment
const financialAnalyzer = new natural.SentimentAnalyzer('English', null, 'afinnFinancialMarketNews');
const financialTokens = natural.WordTokenizer.tokenize('The stock market crashed today');
const financialScore = financialAnalyzer.getSentiment(financialTokens);
console.log(financialScore);const natural = require('natural');
/**
* Complete sentiment analysis function
* @param text - Raw text to analyze
* @param language - Language for analysis (default: 'English')
* @param type - Sentiment lexicon type (default: 'afinn')
* @param stemmer - Optional stemmer (default: PorterStemmer for English)
* @returns Object with score and classification
*/
function analyzeSentiment(text, language = 'English', type = 'afinn', stemmer = natural.PorterStemmer) {
// Create analyzer
const analyzer = new natural.SentimentAnalyzer(language, stemmer, type);
// Tokenize text
const tokens = natural.WordTokenizer.tokenize(text.toLowerCase());
// Get sentiment score
const score = analyzer.getSentiment(tokens);
// Classify sentiment
let classification;
if (score > 0) {
classification = 'positive';
} else if (score < 0) {
classification = 'negative';
} else {
classification = 'neutral';
}
return {
score,
classification,
tokens
};
}
// Example usage
const result = analyzeSentiment('I absolutely love this fantastic movie!');
console.log(result);
// { score: 6, classification: 'positive', tokens: [...] }
const negativeResult = analyzeSentiment('This movie is boring and terrible');
console.log(negativeResult);
// { score: -4, classification: 'negative', tokens: [...] }const natural = require('natural');
/**
* Analyze sentiment for multiple texts
* @param texts - Array of text strings
* @param options - Analysis options
* @returns Array of sentiment results
*/
function batchSentimentAnalysis(texts, options = {}) {
const {
language = 'English',
type = 'afinn',
stemmer = natural.PorterStemmer
} = options;
const analyzer = new natural.SentimentAnalyzer(language, stemmer, type);
return texts.map(text => {
const tokens = natural.WordTokenizer.tokenize(text.toLowerCase());
const score = analyzer.getSentiment(tokens);
return {
text,
score,
classification: score > 0 ? 'positive' : score < 0 ? 'negative' : 'neutral'
};
});
}
// Example usage
const reviews = [
'This product is amazing and I love it!',
'Terrible quality, waste of money',
'It works fine, nothing special',
'Outstanding service and great value'
];
const results = batchSentimentAnalysis(reviews);
results.forEach(result => {
console.log(`"${result.text}" -> ${result.classification} (${result.score})`);
});const natural = require('natural');
// Spanish AFINN
const spanishAnalyzer = new natural.SentimentAnalyzer('Spanish', null, 'afinn');
const spanishTexts = [
'Me encanta este producto',
'Es terrible y horrible',
'Está bien, nada especial'
];
spanishTexts.forEach(text => {
const tokens = natural.WordTokenizer.tokenize(text.toLowerCase());
const score = spanishAnalyzer.getSentiment(tokens);
console.log(`"${text}" -> ${score}`);
});
// Spanish SentiCon
const senticonAnalyzer = new natural.SentimentAnalyzer('Spanish', null, 'senticon');
const senticonScore = senticonAnalyzer.getSentiment(['bueno', 'excelente', 'fantástico']);
console.log('SentiCon score:', senticonScore);const natural = require('natural');
const dutchAnalyzer = new natural.SentimentAnalyzer('Dutch', null, 'pattern');
const dutchTexts = [
'Dit is geweldig en fantastisch',
'Verschrikkelijk en afschuwelijk',
'Het is oké, niets bijzonders'
];
dutchTexts.forEach(text => {
const tokens = natural.WordTokenizer.tokenize(text.toLowerCase());
const score = dutchAnalyzer.getSentiment(tokens);
console.log(`"${text}" -> ${score}`);
});const natural = require('natural');
const financialAnalyzer = new natural.SentimentAnalyzer('English', null, 'afinnFinancialMarketNews');
const financialNews = [
'Stock prices soared after positive earnings report',
'Market crashed due to economic uncertainty',
'Steady growth expected in technology sector',
'Investors panic as oil prices plummet'
];
financialNews.forEach(news => {
const tokens = natural.WordTokenizer.tokenize(news.toLowerCase());
const score = financialAnalyzer.getSentiment(tokens);
const sentiment = score > 0 ? 'bullish' : score < 0 ? 'bearish' : 'neutral';
console.log(`"${news}" -> ${sentiment} (${score})`);
});const natural = require('natural');
/**
* Advanced sentiment analysis with preprocessing
*/
class AdvancedSentimentAnalyzer {
constructor(language = 'English', type = 'afinn') {
this.analyzer = new natural.SentimentAnalyzer(language, natural.PorterStemmer, type);
this.stemmer = natural.PorterStemmer;
}
/**
* Preprocess text before sentiment analysis
* @param text - Raw text
* @returns Processed tokens
*/
preprocessText(text) {
// Convert to lowercase
text = text.toLowerCase();
// Remove URLs
text = text.replace(/https?:\/\/[^\s]+/g, '');
// Remove mentions and hashtags
text = text.replace(/@\w+|#\w+/g, '');
// Tokenize
let tokens = natural.WordTokenizer.tokenize(text);
// Remove stopwords
tokens = tokens.filter(token => !natural.stopwords.includes(token));
// Stem tokens
tokens = tokens.map(token => this.stemmer.stem(token));
return tokens;
}
/**
* Analyze sentiment with preprocessing
* @param text - Raw text
* @returns Sentiment analysis result
*/
analyze(text) {
const tokens = this.preprocessText(text);
const score = this.analyzer.getSentiment(tokens);
return {
originalText: text,
processedTokens: tokens,
score,
classification: score > 0 ? 'positive' : score < 0 ? 'negative' : 'neutral'
};
}
}
// Example usage
const advancedAnalyzer = new AdvancedSentimentAnalyzer();
const socialMediaPost = "OMG I absolutely LOVE this new phone! Best purchase ever! #awesome @company";
const result = advancedAnalyzer.analyze(socialMediaPost);
console.log(result);