The Wayback Machine - https://web.archive.org/web/20240921213434/https://www.geeksforgeeks.org/twitter-sentiment-analysis-using-python/
Open In App

Twitter Sentiment Analysis using Python

Last Updated : 07 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

This article covers the sentiment analysis of any topic by parsing the tweets fetched from Twitter using Python.

What is sentiment analysis?
Sentiment Analysis is the process of ‘computationally’ determining whether a piece of writing is positive, negative or neutral. It’s also known as opinion mining , deriving the opinion or attitude of a speaker.


If you want to learn python for the analysis and how we handle these things in python then you should check out our comprehensive course on the python in which we have cover all the basics you need

Why sentiment analysis?

  • Business: In marketing field companies use it to develop their strategies, to understand customers’ feelings towards products or brand, how people respond to their campaigns or product launches and why consumers don’t buy some products.
  • Politics: In political field, it is used to keep track of political view, to detect consistency and inconsistency between statements and actions at the government level. It can be used to predict election results as well!
  • Public Actions: Sentiment analysis also is used to monitor and analyse social phenomena, for the spotting of potentially dangerous situations and determining the general mood of the blogosphere.

Installation:

  • Tweepy: tweepy is the python client for the official Twitter API . Install it using following pip command:
pip install tweepy
  • TextBlob: textblob is the python library for processing textual data. Install it using following pip command:
pip install textblob
  • Also, we need to install some NLTK corpora using following command:
python -m textblob.download_corpora
  • (Corpora is nothing but a large and structured set of texts.)

Authentication: In order to fetch tweets through Twitter API, one needs to register an App through their twitter account. Follow these steps for the same:

  • Open this link and click the button: ‘Create New App’
  • Fill the application details. You can leave the callback url field empty.
  • Once the app is created, you will be redirected to the app page.
  • Open the ‘Keys and Access Tokens’ tab.
  • Copy ‘Consumer Key’, ‘Consumer Secret’, ‘Access token’ and ‘Access Token Secret’.

Implementation:

Python
import re
import tweepy
from tweepy import OAuthHandler
from textblob import TextBlob

class TwitterClient(object):
    '''
    Generic Twitter Class for sentiment analysis.
    '''
    def __init__(self):
        '''
        Class constructor or initialization method.
        '''
        # keys and tokens from the Twitter Dev Console
        consumer_key = 'XXXXXXXXXXXXXXXXXXXXXXXX'
        consumer_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
        access_token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'
        access_token_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXX'

        # attempt authentication
        try:
            # create OAuthHandler object
            self.auth = OAuthHandler(consumer_key, consumer_secret)
            # set access token and secret
            self.auth.set_access_token(access_token, access_token_secret)
            # create tweepy API object to fetch tweets
            self.api = tweepy.API(self.auth)
        except:
            print("Error: Authentication Failed")

    def clean_tweet(self, tweet):
        '''
        Utility function to clean tweet text by removing links, special characters
        using simple regex statements.
        '''
        return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])
                                    |(\w+:\/\/\S+)", " ", tweet).split())

    def get_tweet_sentiment(self, tweet):
        '''
        Utility function to classify sentiment of passed tweet
        using textblob's sentiment method
        '''
        # create TextBlob object of passed tweet text
        analysis = TextBlob(self.clean_tweet(tweet))
        # set sentiment
        if analysis.sentiment.polarity > 0:
            return 'positive'
        elif analysis.sentiment.polarity == 0:
            return 'neutral'
        else:
            return 'negative'

    def get_tweets(self, query, count = 10):
        '''
        Main function to fetch tweets and parse them.
        '''
        # empty list to store parsed tweets
        tweets = []

        try:
            # call twitter api to fetch tweets
            fetched_tweets = self.api.search(q = query, count = count)

            # parsing tweets one by one
            for tweet in fetched_tweets:
                # empty dictionary to store required params of a tweet
                parsed_tweet = {}

                # saving text of tweet
                parsed_tweet['text'] = tweet.text
                # saving sentiment of tweet
                parsed_tweet['sentiment'] = self.get_tweet_sentiment(tweet.text)

                # appending parsed tweet to tweets list
                if tweet.retweet_count > 0:
                    # if tweet has retweets, ensure that it is appended only once
                    if parsed_tweet not in tweets:
                        tweets.append(parsed_tweet)
                else:
                    tweets.append(parsed_tweet)

            # return parsed tweets
            return tweets

        except tweepy.TweepError as e:
            # print error (if any)
            print("Error : " + str(e))

def main():
    # creating object of TwitterClient Class
    api = TwitterClient()
    # calling function to get tweets
    tweets = api.get_tweets(query = 'Donald Trump', count = 200)

    # picking positive tweets from tweets
    ptweets = [tweet for tweet in tweets if tweet['sentiment'] == 'positive']
    # percentage of positive tweets
    print("Positive tweets percentage: {} %".format(100*len(ptweets)/len(tweets)))
    # picking negative tweets from tweets
    ntweets = [tweet for tweet in tweets if tweet['sentiment'] == 'negative']
    # percentage of negative tweets
    print("Negative tweets percentage: {} %".format(100*len(ntweets)/len(tweets)))
    # percentage of neutral tweets
    print("Neutral tweets percentage: {} % \
        ".format(100*(len(tweets) -(len( ntweets )+len( ptweets)))/len(tweets)))

    # printing first 5 positive tweets
    print("\n\nPositive tweets:")
    for tweet in ptweets[:10]:
        print(tweet['text'])

    # printing first 5 negative tweets
    print("\n\nNegative tweets:")
    for tweet in ntweets[:10]:
        print(tweet['text'])

if __name__ == "__main__":
    # calling main function
    main()

Here is how a sample output looks like when above program is run:

Positive tweets percentage: 22 %
Negative tweets percentage: 15 %


Positive tweets:
RT @JohnGGalt: Amazing—after years of attacking Donald Trump the media managed
to turn #InaugurationDay into all about themselves.
#MakeAmeâ€Ķ
RT @vooda1: CNN Declines to Air White House Press Conference Live YES!
THANK YOU @CNN FOR NOT LEGITIMIâ€Ķ
RT @Muheeb_Shawwa: Donald J. Trump's speech sounded eerily familiar...
POTUS plans new deal for UK as Theresa May to be first foreign leader to meet new
president since inauguration
.@realdonaldtrump #Syria #Mexico #Russia & now #Afghanistan.
Another #DearDonaldTrump Letter worth a read @AJEnglish


Negative tweets:
RT @Slate: Donald Trump’s administration: “Government by the worst men.”
RT @RVAwonk: Trump, Sean Spicer, etc. all lie for a reason.
Their lies are not just lies. Their lies are authoritarian propaganda.
RT @KomptonMusic: Me: I hate corn
Donald Trump: I hate corn too
Me: https://t.co/GPgy8R8HB5
It's ridiculous that people are more annoyed at this than Donald Trump's sexism.
RT @tony_broach: Chris Wallace on Fox news right now talking crap
about Donald Trump news conference it seems he can't face the truth eitherâ€Ķ
RT @fravel: With False Claims, Donald Trump Attacks Media on Crowd Turnout
Aziz Ansari Just Hit Donald Trump Hard In An Epic Saturday Night Live Monologue

We follow these 3 major steps in our program:

  • Authorize twitter API client.
  • Make a GET request to Twitter API to fetch tweets for a particular query.
  • Parse the tweets. Classify each tweet as positive, negative or neutral.

Now, let us try to understand the above piece of code:

  • First of all, we create a TwitterClient class. This class contains all the methods to interact with Twitter API and parsing tweets. We use __init__ function to handle the authentication of API client.
  • In get_tweets function, we use:
fetched_tweets = self.api.search(q = query, count = count)
  • to call the Twitter API to fetch tweets.
  • In get_tweet_sentiment we use textblob module.
analysis = TextBlob(self.clean_tweet(tweet))
  • TextBlob is actually a high level library built over top of NLTK library. First we call clean_tweet method to remove links, special characters, etc. from the tweet using some simple regex. Then, as we pass tweet to create a TextBlob object, following processing is done over text by textblob library:
    • Tokenize the tweet ,i.e split words from body of text.
    • Remove stopwords from the tokens.(stopwords are the commonly used words which are irrelevant in text analysis like I, am, you, are, etc.)
    • Do POS( part of speech) tagging of the tokens and select only significant features/tokens like adjectives, adverbs, etc.
    • Pass the tokens to a sentiment classifier which classifies the tweet sentiment as positive, negative or neutral by assigning it a polarity between -1.0 to 1.0 .
    • TextBlob uses a Movies Reviews dataset in which reviews have already been labelled as positive or negative.
    • Positive and negative features are extracted from each positive and negative review respectively.
    • Training data now consists of labelled positive and negative features. This data is trained on a Naive Bayes Classifier .
  • Finally, parsed tweets are returned. Then, we can do various type of statistical analysis on the tweets. For example, in above program, we tried to find the percentage of positive, negative and neutral tweets about a query.

Full Code Explanation:

  1. The code first creates a RandomForestRegressor object.
  2. This object is used to train a model that predicts air quality index (AQI) values.
  3. Next, the code separates the class label (train) and other attributes (target).
  4. The train data set contains information about air quality index values for different classes, while the target data set contains only AQI values.
  5. The code then fits the RandomForestRegressor object on the train data set and targets the predicted AQI value in the target data set.
  6. The code creates a model using the RandomForestRegressor algorithm.
  7. The model is fit to data consisting of air quality index values from training data and target values for air quality index.
  8. The code in this section is used to train a Random Forest Regressor.
  9. A Random Forest Regressor is a machine learning algorithm that uses a collection of trees (or forests) to make predictions.
  10. The first thing the code does is set some parameters.
  11. The most important parameter is the bootstrap parameter, which determines how often the training data should be randomly sampled from.
  12. The default value is True, which means that the training data will be randomly sampled every time it’s needed.
  13. Another important parameter is ccp_alpha, which controls how much weight should be given to features when making predictions.
  14. By default, ccp_alpha is set to 0.0, which means that all features are equally important when making predictions.
  15. However, if you want more weight to be given to certain features over others, you can set ccp_alpha to a value between 0 and 1 .
  16. If you set ccp_alpha too low (i.e., less than 0), then the feature with the lowest importance will have the most weight in predicting outcomes; if you set ccp_alpha too high (i.e., greater than 1), then the feature with the highest importance will have the most weight in predicting outcomes.
  17. The next thing
  18. The code will create a Random Forest Regressor to predict sales.
  19. The Random Forest Regressor will use bootstrap sampling to generate samples, and will have a criterion of mse.
  20. The Random Forest Regressor will also have a max_depth and max_features parameter.
  21. The max_depth parameter controls the maximum number of layers in the Random Forest Regressor, while the max_features parameter controls the number of features that are used in the model.
  22. Finally, the code specifies that the Random Forest Regressor should have a min_impurity_decrease and min_impurity_split parameter.
  23. These parameters control how aggressively the model should try to reduce impurity (i.e., variance).
  24. Lastly, the code specifies that the Random
  25. The code begins by importing the necessary modules.
  26. The AdaBoostRegressor module is used to create and fit the model.
  27. The learning_rate, loss, and n_estimators parameters are all optional; they can be left at their default values (1.0, ‘linear’, and 50, respectively).
  28. Next, the base_estimator parameter is set to None.
  29. This means that the model will be fitted using a random forest algorithm instead of a simple linear regression model.
  30. The next step is to define the model parameters.
  31. The learning_rate parameter sets how often the algorithm should learn from data; it should be greater than 1 but less than or equal to 2 (in this case, 1.0).
  32. The loss parameter specifies how much weight each prediction should have in determining the final score; it should be ‘linear’ in this case (meaning that predictions with lower scores will have less impact on the final score).
  33. Finally, n_estimators defines how many trees will be used in the random forest algorithm; 50 is used here.
  34. After defining these parameters, it’s time to fit the model!
  35. First, train1 and target are passed into the fit() method as input data.
  36. Next, m2
  37. The code first imports the AdaBoostRegressor module.
  38. This module allows you to train a model using a gradient descent algorithm.
  39. Next, the code defines the model using the AdaBoostRegressor() function.
  40. The parameters that are defined include the base estimator (which is None in this case), learning rate (1.0), and loss (linear).
  41. Finally, the code sets up 50 training iterations and passes in the target value as an input.
  42. After fitting the model, the predicted values for each sample are returned.

References:




Previous Article
Next Article

Similar Reads

Twitter Sentiment Analysis WebApp Using Flask
This is a web app made using Python and Flask Framework. It has a registration system and a dashboard. Users can enter keywords to retrieve live Twitter text based on the keyword, and analyze it for customer feelings and sentiments. This data can be visualized in a graph. This project, in particular, mines data using a popular “Tweepy” API. Tweepy
15+ min read
Python | Sentiment Analysis using VADER
Sentiment Analysis is the process of ‘computationally’ determining whether a piece of writing is positive, negative or neutral. It’s also known as opinion mining, deriving the opinion or attitude of a speaker.Why sentiment analysis? Business: In marketing field companies use it to develop their strategies, to understand customers’ feelings towards
3 min read
Python - Sentiment Analysis using Affin
Afinn is the simplest yet popular lexicons used for sentiment analysis developed by Finn Årup Nielsen. It contains 3300+ words with a polarity score associated with each word. In python, there is an in-built function for this lexicon. Let's see its syntax- Installing the library: C/C++ Code # code print("GFG") pip install afinn /
2 min read
Tweet Sentiment Analysis Using Python Streamlit
This article covers the sentiment analysis of by parsing the tweets fetched from Twitter using the streamlit Python framework. What is Sentiment Analysis? Sentiment Analysis is the process of ‘computationally’ determining whether a piece of writing is positive, negative or neutral. It’s also known as opinion mining, deriving the opinion or attitude
4 min read
Create a Simple Sentiment Analysis WebApp using Streamlit
In this article, we will see how we can create a simple Sentiment Analysis webApp using with the help of Streamlit Module in Python. Required Modules: For this, we will need Three Modules. StreamlitTextBlobStreamlit_extras (optional). The module Streamlit_extras is optional because it will be used to add some extra features which will not affect th
4 min read
Sentiment Analysis using JavaScript and API
Sentiment Analysis - Sentiment analysis, also known as opinion mining, is a computational technique used to determine and categorize the emotional tone or attitude expressed in a piece of text. Analyzing sentiment in text is a crucial task in natural language processing, allowing us to understand the emotional tone and attitude of the content. In t
4 min read
Sentiment Analysis with an Recurrent Neural Networks (RNN)
Recurrent Neural Networks (RNN) are to the rescue when the sequence of information is needed to be captured (another use case may include Time Series, next word prediction, etc.). Due to its internal memory factor, it remembers past sequences along with current input which makes it capable to capture context rather than just individual words. For b
7 min read
Sentiment Detector GUI using Tkinter - Python
Prerequisites : Introduction to tkinter | Sentiment Analysis using Vader Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. Python with Tkinter outputs the fastest and easiest way to create GUI applications. In this article, we will learn how to creat
4 min read
Python | TextBlob.sentiment() method
With the help of TextBlob.sentiment() method, we can get the sentiments of the sentences by using TextBlob.sentiment() method. Syntax : TextBlob.sentiment() Return : Return the tuple of sentiments. Example #1 : In this example we can say that by using TextBlob.sentiment() method, we are able to get the sentiments of a sentence. # import TextBlob fr
1 min read
Twitter Automation using Selenium Python
If you are someone like me who considers Twitter to be far better than Instagram, then I might be having something for you. We all know gaining followers on twitter can be pretty tough but sometimes retweeting quality content can gain you, followers, too. Obviously, you are a busy person and you don't have time to sit around on your phone or laptop
6 min read
Login Twitter using Python Selenium
Project Description:- Here, we're going to study a simple how-to log in twitter by selenium. Selenium is a free tool for automated trying out across exceptional browsers. Requirement: Selenium – Selenium Python Introduction and Installation Below are the steps: First, go to the twitter website using this Link.Then click on investigate element by ur
2 min read
twitter-text-python (ttp) module - Python
twitter-text-python is a Tweet parser and formatter for Python. Amongst many things, the tasks that can be performed by this module are : reply : The username of the handle to which the tweet is being replied to. users : All the usernames mentioned in the tweet. tags : All the hashtags mentioned in the tweet. urls : All the URLs mentioned in the tw
3 min read
Apache Kafka - Real World Project with Twitter using Java
Apache Kafka is a publish-subscribe messaging system. A messaging system let you send messages between processes, applications, and servers. Apache Kafka is software where topics (A topic might be a category) can be defined and further processed. To know more about this, please refer to the article - What is Apache Kafka and How Does it Work? In th
5 min read
Create Twitter Login Page using Tailwind & jQuery
We will see How To Make a Twitter Login Page Using TailwindCSS and jQuery. The code produces an attractive login page with a design similar to the Twitter login interface. The jQuery incorporates straightforward validation for the email input field upon submitting the form. PrerequisitesHTMLTailwind CSSjQueryApproachThe HTML code outlines a basic l
2 min read
OAuth Authentication with Flask - Connect to Google, Twitter, and Facebook
In this article, we are going to build a flask application that will use the OAuth protocol to get user information. First, we need to understand the OAuth protocol and its procedure. What is OAuth? OAuth stands for Open Authorization and was implemented to achieve a connection between online services. The OAuth Community Site defines it as “An ope
8 min read
Designing Twitter - A System Design Interview Question
Designing Twitter (or Facebook feed or Facebook search..) is a quite common question that interviewers ask candidates. A lot of candidates get afraid of this round more than the coding round because they don't get an idea of what topics and tradeoffs they should cover within this limited timeframe. Important Topics for Designing Twitter How Would Y
15+ min read
Macronutrient analysis using Fitness-Tools module in Python
A good diet is an integral aspect of a balanced lifestyle. It defines the well-being of a human being. Nutrients are divided into two categories i.e macronutrients and micronutrients. Macronutrients are the nutrition that the body needs a large amount. Macronutrients provide calories or energy on the other hand micronutrients are those nutrients th
2 min read
Material Analysis using Python
Using basic principles of more than one field to solve a complicated problem might be very difficult to reach by using one area of knowledge. With this kind of approach, one can also redefine problems outside usual boundaries and reach solutions using a new understanding of impenetrable situations which early considered impossible to get. Material
7 min read
Zomato Data Analysis Using Python
Python and its following libraries are used to analyze Zomato data. Numpy- With Numpy arrays, complex computations are executed quickly, and large calculations are handled efficiently.Matplotlib- It has a wide range of features for creating high-quality plots, charts, histograms, scatter plots, and more.Pandas- The library simplifies the loading of
4 min read
Correspondence Analysis using Python
Correspondence Analysis (CA) is a statistical technique used to analyze the relationships between the categorical variables in a contingency table. It provides a visual representation of the data allowing for the identification of the patterns and associations between the categories of the variables. What is Correspondence Analysis?Correspondence a
4 min read
Data analysis using Pandas
Pandas are the most popular python library that is used for data analysis. It provides highly optimized performance with back-end source code purely written in C or Python. We can analyze data in Pandas with: Pandas SeriesPandas DataFramesPandas Series Series in Pandas is one dimensional(1-D) array defined in pandas that can be used to store any da
4 min read
Image Analysis Tool using PyQtGraph
In this article we will see how we can perform common image analysis using PyQtGraph module in Python. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.)
5 min read
Restaurant Review Analysis Using NLP and SQLite
Normally, a lot of businesses are remained as failures due to lack of profit, lack of proper improvement measures. Mostly, restaurant owners face a lot of difficulties to improve their productivity. This project really helps those who want to increase their productivity, which in turn increases their business profits. This is the main objective of
9 min read
GE Stock Price Analysis Using R Language
Stock analysis is a technique used by investors and traders to make purchasing and selling choices. Investors and traders strive to obtain an advantage in the markets by making educated judgments by researching and analyzing previous and current data. In this article, we will analyze the 'GE Stock Price' dataset using the R Programming Language. Th
5 min read
Project Idea | Personality Analysis using hashtags from tweets
Introduction The project is based on the concept of analyzing the personality of an individual, and plotting the sentiments of tweets according to user/community location.Our application would consider the actual mentality of the individuals along with the situation and topic and assess their personality accordingly. Conceptual Framework Our approa
5 min read
Project Idea | Analysis of Emergency 911 calls using Association Rule Mining
Introduction Analysing emergency calls dataset and discovering hidden trends and patterns will help in ensuring that the emergency response team is better equipped to deal with emergencies. Considering road accidents, fire accidents etc, high numbers in specific areas indicate that there is a high demand for ambulance services in those areas. Road
7 min read
Replacing strings with numbers in Python for Data Analysis
Sometimes we need to convert string values in a pandas dataframe to a unique integer so that the algorithms can perform better. So we assign unique numeric value to a string value in Pandas DataFrame. Note: Before executing create an example.csv file containing some names and gender Say we have a table containing names and gender column. In gender
3 min read
Detailed Analysis on affects of Dynamic Typing and Concurrency on Python?
Is python too slow? The reality is, Python is an extremely slow programming language when we look at something like Java, C, and C++ it's embarrassing how much faster they can do things than Python, in fact, specific algorithms and applications can actually do things about a hundred to two hundred times faster than the native Python language so in
7 min read
Introduction to Power Analysis in Python
To understand what power analysis is, we must first take a look at the concepts of a statistical hypothesis test. A statistical hypothesis test calculates some quantity under a given assumption (null hypothesis) and the result of the test allows us to interpret whether the assumption is valid or whether the assumption has been violated. A violation
6 min read
Pandas Functions in Python: A Toolkit for Data Analysis
Pandas is one of the most used libraries in Python for data science or data analysis. It can read data from CSV or Excel files, manipulate the data, and generate insights from it. Pandas can also be used to clean data, filter data, and visualize data. Whether you are a beginner or an experienced professional, Pandas functions can help you to save t
6 min read
Article Tags :
Practice Tags :