Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

How to Build a Twitter Sentiment Analysis Python Program? [Step-by-Step Tutorial]How to Build a Twit

Updated on 11 January, 2024

8.13K+ views
9 min read

Source

As companies are becoming increasingly data-driven, a Machine Learning technique called ‘Sentiment Analysis’ is gaining immense popularity day by day. It analyses the digital data/text through Natural Language Processing (NLP) to find the polarity (positive, negative, neutral), feelings, and emotions (angry, happy, sad, etc.) expressed in the text. 

Since Twitter is one of the most comprehensive sources of live, public conversation worldwide, business firms, political groups, etc. are interested in performing ‘Sentiment Analysis’ of tweets to understand the emotions/opinions of the target market or for studying competitors’ market. Although they are ready to use programs for the purpose but to achieve predictions with a high level of accuracy, specific to particular criteria and domains, the best way is to create a customized Twitter Sentiment Analysis Python model or program.

Enrol for the Machine Learning Course from the World’s top Universities. Earn Masters, Executive PGP, or Advanced Certificate Programs to fast-track your career.

Step-by-step Tutorial: Create Twitter Sentiment Analysis Program Using Python

This tutorial aims to create a Twitter Sentiment Analysis Program using Python. The resultant program should be capable of parsing the tweets fetched from twitter and understanding the text’s sentiments, like its polarity and subjectivity.

The Perquisites

1. Foremost is the basic coding/programming knowledge of Python.

2. Tools to be installed on your computer:

  • Python
  • Libraries: Tweepy, text blob, word cloud, pandas, NumPy, matplotlib

(Tweepy is the official python library for twitter API that enables Python to communicate with Twitter platform)

3. A Twitter Account 

4. A Twitter App needs to be created and authenticated by Twitter: This is necessary to get the ‘Consumer key and Access tokens’ that you will need in your programming.

If you already don’t have a Twitter App created for the purpose, then here is how to create it.

Read more: Python NumPy Tutorial: Learn Python Numpy With Examples

How to Create a Twitter App?

  • Go to the Twitter developer site: dev.twitter.com.
  • Sign in with your Twitter account
  • Go to ‘My applications’
  • Click on ‘Create a new application.’
  • Next, you need to fill a form, as shown below. 

Source

  • Next, click on ‘Create my Access Token.’
  • In the next page, choose the ‘Read and Write’ option under the column ‘Application Type.’

You will be provided with your Twitter App OAuth Settings, which includes all necessary details related to your consumer key, consumer secret, Access token, Access token secret, etc. You need to note these details as these API credentials will enable you to fetch tweets from twitter. Better to save it in a CSV file in your computer, latter you can directly upload the CSV file into your program to read API credentials

Get Started with Creating Twitter Sentiment Analysis Python Program

1. Import the Libraries: Tweepy, text blob, word cloud, pandas, NumPy, matplotlib 

2. Authenticate the Twitter App: Next, you need to authenticate your twitter app using the Twitter App OAuth Settings credentials, also referred to as Twitter API credentials. For this, you need to create an Authentication object, using the codes as shown in the image below. 

Source

To fill up the Twitter API credentials, you can either upload the CSV file or manually copy paste the credential details. 

3. Fetch the Tweets from the Twitter User: Now, for fetching the tweets, you first need to choose a Twitter user whose tweets you want to parse to understand the sentiment expressed in it. Let’s say; you want to see whether the tweets of ‘UserXYZ’ are positive or negative or neutral by performing sentiment analysis of the 100 tweets by the UserXYZ. 

Code for fetching the tweets

posts = api.user_timeline(screen_name = ”UserXYZ”, count= 100, Lang =”en”, tweet_mode=“extended”)

Running the above command will show up the tweets.  

4. Create Data Frame: Now, you need to create a data frame for the tweets you have fetched. Let’s say you name the first column of your df as ‘Tweets’, and it will contain all the tweets spread across 100 rows since you are analyzing 100 tweets. 

Df = pd.dataframe( [tweet.full_text for tweet in posts] , columns=[ ‘Tweet’])

5. Clean the Text: Cleaning the text of the tweets is important for the success of your twitter sentiment analysis python program, as there will be many unwanted symbols like @, #, re-tweets, hyperlinks in the URLs, etc. Here your python’’ library gets into use. 

Get the Subjectivity and Polarity: Once you have cleaned the text, you need to create two functions using the TextBlob python library to get the tweets’ subjectivity and polarity. The subjectivity shows how opinionated the text is, and polarity describes the positivity or negativity of the text. It would be best to write the python script to create two more columns in your data frame to host Subjectivity and Polarity. So, now your data frame will have three columns (first for the tweets, 2nd for the subjectivity, 3rd for the polarity)

The codes for creating Subjectivity and Polarity functions are as follows:

Source

After you run the code, you will see the scores of subjectivity and polarity of each tweet shown in the respective columns. TextBlob describes the polarity within a scale of 1 to -1. So, if a tweet has -0.4 polarity means it’s slightly negative, and if it has 0.6 subjectivity, then it is fairly subjective. 

6. Next, you can choose to include a word cloud in your Twitter Sentiment Analysis Python program, as word clouds are also popular as a data visualization technique used for sentiment analysis, wherein the size of the words indicates its importance. 

Example of a WordCloud:

Source

The matplotlib, Pandas, and WordCloud libraries will come into action that you have already imported. To plot a word cloud-first, you need to create a variable; let’s name it ‘allwords’ to represent all the tweets in the ‘Tweets’ column of the data frame.  

Code for creating WordCloud

allwords = ‘ ‘.join( [twts for twts in df [ ‘Tweets’ ]] )

WordCloud = WordCloud (width =xxx, height =xxx, randon_state =xxx, max_font_size =xxx. generate (allwords) 

plt.imshow(wordcloud) 

plt.axis(“off”) 

plt.show() 

7. As you have the polarity scores for each tweet, you can start to compute positive, negative, and neutral analysis of the tweets. For this, you need to create a function, let’s call it ‘Analysis’, wherein you can assign the score 0 to neutral, <0 to negative, and >0 to positive. 

Def Analysis(score): 

 If score < 0

return ‘Negative.’

elif score == 0

return ‘neutral

else, 

return ‘positive.’

Next, to host the results of the sentiment analysis of the tweets, create a new column in your data frame, let’s name it ‘TwtAnalysis’ and then write the following code:

df [ ‘TwtAnalysis’ ] = df [ ‘Polarity’ ]. apply(Analysis)

8. The new data frame will have the added column named ‘TwtAnalysis’, and it will refer to each tweet either as positive, negative, or neutral based on its polarity score. An example is shown below in the image:

Source

9. Once you have the classification of the tweets as positive, negative, and neutral, you can continue building your Twitter Sentiment Analysis Python program to represent the data in different formats such as:

  • Get the percentage of positive, negative, or neutral tweets.
  • Print all of the positive comments or negative or neutral tweets separately
  • Create a visual sentiment analysis chart of the positive, negative, and neutral tweets, and much more.

Also Read: Top 9 Python Libraries for Machine Learning

Check out all trending Python tutorial concepts in 2024.

Conclusion

The Twitter Sentiment Analysis Python programexplained in this article, is just one way to create such a program. The developer can customize the program in many ways to match the specifications for achieving utmost accuracy in the data reading, that is the beauty of programming it through python, which is a great language, supported by an active community of developers and too many libraries. 

Python holds immense scope in the space of Machine Learning and Data Science. Those who are into programming for a while know it well that Machine Learning will continue to be one of the breakthroughs in the future of programming.

If you want to get a comprehensive and structured learning experience, also if you’re interested to learn more about machine learning, check out IIIT-B & upGrad’s PG Diploma in Machine Learning & AI which is designed for working professionals and offers 450+ hours of rigorous training, 30+ case studies & assignments, IIIT-B Alumni status, 5+ practical hands-on capstone projects & job assistance with top firms.

Frequently Asked Questions (FAQs)

1. What is the functional importance of sentiment analysis on social media?

In this age of social media, consumer opinions hold infinite power to make or break a brand. Sentiment analysis is the best way to understand the driving factors behind consumer opinions and emotions accurately. With data available from sentiment analysis, businesses can find their target audience, identify social media influencers for their brand, and spot emerging market trends. Moreover, sentiment analysis on social media platforms also offers a comprehensive idea of their brand health; businesses can receive honest consumer feedback about their newly launched products and services to improve thereupon. It is also effective in handling online reputation by better identifying scopes of improvement and problem resolution.

2. Can you learn Python on your own?

If you have some level of experience with programming, you can certainly start learning Python on your own. Python comes with a comparatively simple syntactic structure and is also intuitive, making it easy to understand even for beginners. Besides, it is easy to install the package and execute it on your machine from anywhere. You can expedite your learning by enrolling in Python courses, attending coding bootcamps. With an active developer community that is always willing to extend support, an abundance of learning resources, and documentation, beginners can learn the fundamentals of Python in about 7-8 weeks.

3. Which is more difficult to learn between Python and C++?

Python and C++ are entirely different programming languages with entirely different behavior and features. However, both strongly support object-oriented programming. But considering the overall Python framework, it is straightforward, much easier, and quicker to learn than C++. In fact, many people learn Python to experience what simple coding feels like. Python is open-source, free, and offers tremendous reliability and ease when it comes to developing complex machine learning applications. While C++ is more efficient in terms of performance, it is not considered suitable over Python for machine learning projects.