sentiment-analysis-textblob
Version:
A Node.js library for sentiment analysis using TextBlob
84 lines (75 loc) • 2.42 kB
JavaScript
const { PythonShell } = require('python-shell');
const path = require('path');
/**
* Attempts to find an available Python executable.
* @returns {string|null} Path to Python executable or null if not found.
*/
function findPythonPath() {
const possibleCommands = ['python', 'python3'];
for (const cmd of possibleCommands) {
try {
require('child_process').execSync(`${cmd} --version`, { stdio: 'ignore' });
return cmd;
} catch (err) {
continue;
}
}
return null;
}
/**
* Analyzes the sentiment of a given text using TextBlob via PythonShell.
* @param {string} text - The text to analyze.
* @param {function} callback - Callback function to handle the result (err, result).
* @returns {void}
*/
function analyzeSentiment(text, callback) {
if (typeof text !== 'string' || text.trim() === '') {
return callback(new Error('Input text must be a non-empty string'), null);
}
const pythonPath = findPythonPath();
if (!pythonPath) {
return callback(new Error('Python not found. Please install Python 3.6+ and add it to PATH.'), null);
}
const options = {
mode: 'text',
pythonPath: pythonPath,
pythonOptions: ['-u'], // Unbuffered output
scriptPath: path.join(__dirname, '../scripts'),
args: [text]
};
console.log('Running Python script with text:', text); // Debug
console.log('Python path:', pythonPath); // Debug
console.log('Script path:', options.scriptPath); // Debug
PythonShell.run('sentiment.py', options)
.then(results => {
try {
const result = JSON.parse(results[0]);
callback(null, result);
} catch (parseError) {
callback(new Error('Failed to parse Python script output'), null);
}
})
.catch(err => {
console.error('PythonShell error:', err);
callback(err, null);
});
}
/**
* Promise-based version of analyzeSentiment.
* @param {string} text - The text to analyze.
* @returns {Promise<Object>} - Resolves with sentiment analysis result { polarity, subjectivity }.
*/
function analyzeSentimentPromise(text) {
return new Promise((resolve, reject) => {
analyzeSentiment(text, (err, result) => {
if (err) {
return reject(err);
}
resolve(result);
});
});
}
module.exports = {
analyzeSentiment,
analyzeSentimentPromise
};