0
# Sentiment Analysis
1
2
Multi-language sentiment analysis using various lexicons and methodologies for determining emotional tone in text. Natural supports multiple sentiment analysis approaches across different languages.
3
4
## Capabilities
5
6
### Sentiment Analyzer
7
8
Main sentiment analysis class supporting multiple languages and sentiment lexicons.
9
10
```javascript { .api }
11
/**
12
* Sentiment analyzer with multi-language and multi-lexicon support
13
* @param language - Target language for analysis
14
* @param stemmer - Optional stemmer for word preprocessing
15
* @param type - Sentiment lexicon type to use
16
*/
17
class SentimentAnalyzer {
18
constructor(language: string, stemmer?: object, type: string);
19
20
/**
21
* Calculate sentiment score for an array of words
22
* @param words - Array of word strings (usually tokens)
23
* @returns Sentiment score (typically negative to positive range)
24
*/
25
getSentiment(words: string[]): number;
26
}
27
```
28
29
### Supported Languages and Types
30
31
**Languages:**
32
- `'English'` - English sentiment analysis
33
- `'Spanish'` - Spanish sentiment analysis
34
- `'Portuguese'` - Portuguese sentiment analysis
35
- `'Dutch'` - Dutch sentiment analysis
36
- `'Italian'` - Italian sentiment analysis
37
- `'French'` - French sentiment analysis
38
- `'German'` - German sentiment analysis
39
- `'Galician'` - Galician sentiment analysis
40
- `'Catalan'` - Catalan sentiment analysis
41
- `'Basque'` - Basque sentiment analysis
42
43
**Sentiment Types:**
44
- `'afinn'` - AFINN lexicon (English, Spanish, Portuguese)
45
- `'afinnFinancialMarketNews'` - AFINN for financial market news (English)
46
- `'senticon'` - SentiCon lexicon (Spanish, English, Galician, Catalan, Basque)
47
- `'pattern'` - Pattern lexicon (Dutch, Italian, English, French, German)
48
49
**Usage Examples:**
50
51
```javascript
52
const natural = require('natural');
53
54
// English AFINN sentiment analysis
55
const analyzer = new natural.SentimentAnalyzer('English', natural.PorterStemmer, 'afinn');
56
57
// Tokenize and analyze
58
const tokens = natural.WordTokenizer.tokenize('I love this amazing product');
59
const score = analyzer.getSentiment(tokens);
60
console.log(score); // Positive score
61
62
// Negative sentiment
63
const negativeTokens = natural.WordTokenizer.tokenize('This is terrible and awful');
64
const negativeScore = analyzer.getSentiment(negativeTokens);
65
console.log(negativeScore); // Negative score
66
67
// Spanish sentiment analysis
68
const spanishAnalyzer = new natural.SentimentAnalyzer('Spanish', null, 'afinn');
69
const spanishTokens = ['me', 'gusta', 'mucho', 'este', 'producto'];
70
const spanishScore = spanishAnalyzer.getSentiment(spanishTokens);
71
console.log(spanishScore);
72
73
// Financial market sentiment
74
const financialAnalyzer = new natural.SentimentAnalyzer('English', null, 'afinnFinancialMarketNews');
75
const financialTokens = natural.WordTokenizer.tokenize('The stock market crashed today');
76
const financialScore = financialAnalyzer.getSentiment(financialTokens);
77
console.log(financialScore);
78
```
79
80
### Complete Sentiment Analysis Pipeline
81
82
```javascript
83
const natural = require('natural');
84
85
/**
86
* Complete sentiment analysis function
87
* @param text - Raw text to analyze
88
* @param language - Language for analysis (default: 'English')
89
* @param type - Sentiment lexicon type (default: 'afinn')
90
* @param stemmer - Optional stemmer (default: PorterStemmer for English)
91
* @returns Object with score and classification
92
*/
93
function analyzeSentiment(text, language = 'English', type = 'afinn', stemmer = natural.PorterStemmer) {
94
// Create analyzer
95
const analyzer = new natural.SentimentAnalyzer(language, stemmer, type);
96
97
// Tokenize text
98
const tokens = natural.WordTokenizer.tokenize(text.toLowerCase());
99
100
// Get sentiment score
101
const score = analyzer.getSentiment(tokens);
102
103
// Classify sentiment
104
let classification;
105
if (score > 0) {
106
classification = 'positive';
107
} else if (score < 0) {
108
classification = 'negative';
109
} else {
110
classification = 'neutral';
111
}
112
113
return {
114
score,
115
classification,
116
tokens
117
};
118
}
119
120
// Example usage
121
const result = analyzeSentiment('I absolutely love this fantastic movie!');
122
console.log(result);
123
// { score: 6, classification: 'positive', tokens: [...] }
124
125
const negativeResult = analyzeSentiment('This movie is boring and terrible');
126
console.log(negativeResult);
127
// { score: -4, classification: 'negative', tokens: [...] }
128
```
129
130
### Batch Sentiment Analysis
131
132
```javascript
133
const natural = require('natural');
134
135
/**
136
* Analyze sentiment for multiple texts
137
* @param texts - Array of text strings
138
* @param options - Analysis options
139
* @returns Array of sentiment results
140
*/
141
function batchSentimentAnalysis(texts, options = {}) {
142
const {
143
language = 'English',
144
type = 'afinn',
145
stemmer = natural.PorterStemmer
146
} = options;
147
148
const analyzer = new natural.SentimentAnalyzer(language, stemmer, type);
149
150
return texts.map(text => {
151
const tokens = natural.WordTokenizer.tokenize(text.toLowerCase());
152
const score = analyzer.getSentiment(tokens);
153
154
return {
155
text,
156
score,
157
classification: score > 0 ? 'positive' : score < 0 ? 'negative' : 'neutral'
158
};
159
});
160
}
161
162
// Example usage
163
const reviews = [
164
'This product is amazing and I love it!',
165
'Terrible quality, waste of money',
166
'It works fine, nothing special',
167
'Outstanding service and great value'
168
];
169
170
const results = batchSentimentAnalysis(reviews);
171
results.forEach(result => {
172
console.log(`"${result.text}" -> ${result.classification} (${result.score})`);
173
});
174
```
175
176
### Language-Specific Examples
177
178
#### Spanish Sentiment Analysis
179
180
```javascript
181
const natural = require('natural');
182
183
// Spanish AFINN
184
const spanishAnalyzer = new natural.SentimentAnalyzer('Spanish', null, 'afinn');
185
186
const spanishTexts = [
187
'Me encanta este producto',
188
'Es terrible y horrible',
189
'Está bien, nada especial'
190
];
191
192
spanishTexts.forEach(text => {
193
const tokens = natural.WordTokenizer.tokenize(text.toLowerCase());
194
const score = spanishAnalyzer.getSentiment(tokens);
195
console.log(`"${text}" -> ${score}`);
196
});
197
198
// Spanish SentiCon
199
const senticonAnalyzer = new natural.SentimentAnalyzer('Spanish', null, 'senticon');
200
const senticonScore = senticonAnalyzer.getSentiment(['bueno', 'excelente', 'fantástico']);
201
console.log('SentiCon score:', senticonScore);
202
```
203
204
#### Dutch Pattern Sentiment
205
206
```javascript
207
const natural = require('natural');
208
209
const dutchAnalyzer = new natural.SentimentAnalyzer('Dutch', null, 'pattern');
210
211
const dutchTexts = [
212
'Dit is geweldig en fantastisch',
213
'Verschrikkelijk en afschuwelijk',
214
'Het is oké, niets bijzonders'
215
];
216
217
dutchTexts.forEach(text => {
218
const tokens = natural.WordTokenizer.tokenize(text.toLowerCase());
219
const score = dutchAnalyzer.getSentiment(tokens);
220
console.log(`"${text}" -> ${score}`);
221
});
222
```
223
224
#### Financial Market Sentiment
225
226
```javascript
227
const natural = require('natural');
228
229
const financialAnalyzer = new natural.SentimentAnalyzer('English', null, 'afinnFinancialMarketNews');
230
231
const financialNews = [
232
'Stock prices soared after positive earnings report',
233
'Market crashed due to economic uncertainty',
234
'Steady growth expected in technology sector',
235
'Investors panic as oil prices plummet'
236
];
237
238
financialNews.forEach(news => {
239
const tokens = natural.WordTokenizer.tokenize(news.toLowerCase());
240
const score = financialAnalyzer.getSentiment(tokens);
241
const sentiment = score > 0 ? 'bullish' : score < 0 ? 'bearish' : 'neutral';
242
console.log(`"${news}" -> ${sentiment} (${score})`);
243
});
244
```
245
246
### Advanced Usage with Preprocessing
247
248
```javascript
249
const natural = require('natural');
250
251
/**
252
* Advanced sentiment analysis with preprocessing
253
*/
254
class AdvancedSentimentAnalyzer {
255
constructor(language = 'English', type = 'afinn') {
256
this.analyzer = new natural.SentimentAnalyzer(language, natural.PorterStemmer, type);
257
this.stemmer = natural.PorterStemmer;
258
}
259
260
/**
261
* Preprocess text before sentiment analysis
262
* @param text - Raw text
263
* @returns Processed tokens
264
*/
265
preprocessText(text) {
266
// Convert to lowercase
267
text = text.toLowerCase();
268
269
// Remove URLs
270
text = text.replace(/https?:\/\/[^\s]+/g, '');
271
272
// Remove mentions and hashtags
273
text = text.replace(/@\w+|#\w+/g, '');
274
275
// Tokenize
276
let tokens = natural.WordTokenizer.tokenize(text);
277
278
// Remove stopwords
279
tokens = tokens.filter(token => !natural.stopwords.includes(token));
280
281
// Stem tokens
282
tokens = tokens.map(token => this.stemmer.stem(token));
283
284
return tokens;
285
}
286
287
/**
288
* Analyze sentiment with preprocessing
289
* @param text - Raw text
290
* @returns Sentiment analysis result
291
*/
292
analyze(text) {
293
const tokens = this.preprocessText(text);
294
const score = this.analyzer.getSentiment(tokens);
295
296
return {
297
originalText: text,
298
processedTokens: tokens,
299
score,
300
classification: score > 0 ? 'positive' : score < 0 ? 'negative' : 'neutral'
301
};
302
}
303
}
304
305
// Example usage
306
const advancedAnalyzer = new AdvancedSentimentAnalyzer();
307
308
const socialMediaPost = "OMG I absolutely LOVE this new phone! Best purchase ever! #awesome @company";
309
const result = advancedAnalyzer.analyze(socialMediaPost);
310
console.log(result);
311
```