Analysing Twitter sentiment via Python

Daniele
Data Tech Tips
Published in
3 min readOct 9, 2018

Hi all, as a data scientist or looking for to be one of us, this kind of analysis could have a serious impact on your career because allows you to understand, first of all, the basis of statistics, how to model your statistic and how to predict behaviour.

For example we want to analyse Tweets based on a specific hashtag, and we want to know if people are reacting with positive or negative manners, and we want to know if this could change somewhat.
Well with python and TextBlob we can achieve this goal with few line codes, let’s see how.

What is TextBlob

TextBlob is a Python (2 and 3) library for processing textual data. It provides a simple API for diving into common natural language processing (NLP) tasks such as part-of-speech tagging, noun phrase extraction, sentiment analysis, classification, translation, and more.
The sentiment property returns a named tuple of the form Sentiment(polarity,subjectivity). The polarity score is a float within the range [-1.0, 1.0]. The subjectivity is a float within the range [0.0, 1.0] where 0.0 is very objective and 1.0 is very subjective.

How to use TwitterAPI

For this task i’ve used Tweepy that gives you an easy way to get tweets via API.
We need from Twitter:
- Consumer key
- Consumer secret
- Access token
- Access token secret
Those elements could be retrieved directly from twitter registering a new app.

The code

Here’s the code:

This code gives you a simple computation over searching a particular hashtag, in this case “ElonMusk” and gives me a result of:

Polarity:
-0.0214646464646
Subjectivity
0.243080808081

This means that the tweets are slightly negative with a modest objectivity of the facts.

With those few lines of code you have created the basis of a Twitter sentiment script in Python and you can complete the analysis with:
- Percent of people talking with good or negative manners
- How many people are talking about this subject
- Etc...

With those data in your hand you can develop simple machine learning algorithm via Tensorflow for example that allows you to predict some simple behaviours.

Some of those algorithms are well explained here , in this case the use of linear or logistic regression could fit well the case.
We want to know if some kind of tweets could help to get better polarity and so on…

In future articles i will explain in detail a linear regression for prediciting traffic delays.

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

This is the basis for developing many topics for some kind of thesis in machine learning and data science! Don’t esitate to write or contact me!
Visit my site: xcloudx8.github.io

--

--