How can I display the count of positive or negative tweets on a twitter sentiment analysis? (python)

I have a project to create a twitter sentiment analysis and display the results of the sentiment on a graph, at first I thought I was meant to display the sentiment of each tweet on a line graph regarding the keyword which the user searches for, but I am meant to show the count of the positive or negative tweets on a bar graph and I am not quite sure how to do that, here is the code

from tweepy import API
from tweepy import Cursor
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream

from textblob import TextBlob

# This will import the data from the twittercredentials file which stores the keys and tokens

import twittercredentials 

import numpy as np
import pandas as pd
import re
import matplotlib.pyplot as plt 

# ----- TWITTER CLIENT ----- #

class TwitterClient():
    def __init__(self, twitter_user=None):
        self.auth = TwitterAuthenticator().authenticate_twitter_app()
        self.twitter_client = API(self.auth)

        self.twitter_user = twitter_user

    def get_twitter_client_api(self):
        return self.twitter_client
    
    def get_tweets(self, query, count = 10):
        
        # Main function to fetch tweets and parse them.
        
        fetched_tweets = self.twitter_client.search(q = query, count = count)
        return fetched_tweets

# ----- TWITTER AUTHENTICATOR ----- #

class TwitterAuthenticator():

    def authenticate_twitter_app(self):
        auth = OAuthHandler(twittercredentials.CONSUMER_KEY, twittercredentials.CONSUMER_SECRET)
        auth.set_access_token(twittercredentials.ACCESS_TOKEN, twittercredentials.ACCESS_TOKEN_SECRET)
        return auth 

# ----- TWEET ANALYSIS ----- #

class TweetAnalyser():
    
    # This class will categorise and analyse the collected tweets

    def clean_tweet(self, tweet):
        return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)", " ", tweet).split())

    def analyse_sentiment(self, tweets):
        analysis = TextBlob(self.clean_tweet(tweets))

        if analysis.sentiment.polarity > 0:
            return 1
        elif analysis.sentiment.polarity == 0:
            return 0
        else:
            return -1

    # This method extracts the text from the tweets and displays it in a readable form

    def tweets_to_data_frame(self, tweets):
        df = pd.DataFrame(data=[tweet.text for tweet in tweets], columns=['tweets'])

        df['id'] = np.array([tweet.id for tweet in tweets])
        df['len'] = np.array([len(tweet.text) for tweet in tweets])
        df['date'] = np.array([tweet.created_at for tweet in tweets])
        df['source'] = np.array([tweet.source for tweet in tweets])
        df['likes'] = np.array([tweet.favorite_count for tweet in tweets])
        df['retweets'] = np.array([tweet.retweet_count for tweet in tweets])
        df['sentiment'] = np.array([tweet_analyser.analyse_sentiment(tweet) for tweet in df['tweets']])

        return df

if __name__ == "__main__":

    twitter_client = TwitterClient()
    tweet_analyser = TweetAnalyser()

    api = twitter_client.get_twitter_client_api()

    search = input("Enter keyword for sentiment analysis: ")
    
    # This is a verification to make sure the user enters a valid integer as the input, if not it will loop until the user 
    # enters a correct input

    while True: 
        amount = input("How many tweets do you want to see?: ")
        try:
            amount = int(amount)
            break 
        except ValueError: 
            print ("Invalid input! Please enter a number")

    tweets = twitter_client.get_tweets(query = search, count = amount)

    df = tweet_analyser.tweets_to_data_frame(tweets)
    
    print(df.head(amount))

    time_sentiment = pd.Series(data=df['sentiment'].values, index=df['date'])
    time_sentiment.plot(figsize=(16, 4), color='r')
    plt.show()

any help would be appreciated



Read more here: https://stackoverflow.com/questions/64940649/how-can-i-display-the-count-of-positive-or-negative-tweets-on-a-twitter-sentimen

Content Attribution

This content was originally published by psmadness at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: