Skip to content

Instantly share code, notes, and snippets.

@AYLIEN
Last active April 22, 2016 09:11
Show Gist options
  • Save AYLIEN/76284718cbbb05d24d94 to your computer and use it in GitHub Desktop.
Save AYLIEN/76284718cbbb05d24d94 to your computer and use it in GitHub Desktop.
Twitter Sentiment Analysis
//**********************************************************************
// Enter the Twitter handle below (var twitterHandle = 'BBCBreaking') to
// see a Sentiment Analysis of the first 10 tweets.
// :-) = positive, :-| = neutral, :-( = negative
//**********************************************************************
var AYLIENTextAPI = require('aylien_textapi'),
request = require('request'),
cheerio = require('cheerio');
var textapi = new AYLIENTextAPI({
application_id: 'YourApplicationId',
application_key: 'YourApplicationKey'
});
var twitterHandle = 'BBCBreaking';
function sentimentToSmiley(sentiment) {
if(sentiment === "neutral") { return ':-|' }
if(sentiment === "negative") { return ':-(' }
else { return ':-)' }
}
function sentiment(text, callback) {
textapi.sentiment(text, function(err, resp) {
if (err !== null) {
console.log("Error: " + err);
} else {
callback(resp.polarity);
}
});
}
request('https://www.twitter.com/' + twitterHandle, function(err, response) {
var $ = cheerio.load(response.body);
var i = 0;
$('.tweet-text').toArray().forEach(function(item) {
var text = $(item).text();
if(i < 10){
i++;
sentiment(text, function(results) {
console.log(sentimentToSmiley(results), '-', text.replace(/\n/g, ' '));
});
} else {return}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment