<jupyter_start><jupyter_text>**Sentiment Analysis on Twitter Data**<jupyter_code>#importing the necessary libraries

import tweepy
from textblob import TextBlob
from wordcloud import WordCloud
import pandas as pd
import numpy as np
import re
import matplotlib.pyplot as plt
from matplotlib.pyplot import *
plt.style.use('fivethirtyeight')

#Load the Data
from google.colab import files
file_uploaded = files.upload()
# get the data
log = pd.read_csv("login.csv")
# Get the API credentials
consumer_key = log['keys'][0]
consumer_secret = log['keys'][1]
access_token = log['keys'][2]
access_token_secret = log['keys'][3]

# Authentication Object
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)

# Set Access Token and Access Token Secret
auth.set_access_token(access_token, access_token_secret) 

# Create API
api = tweepy.API(auth, wait_on_rate_limit = True)
# Extract 1000 tweets from the twitter user
tweets = api.user_timeline(screen_name = "WHO", count = 100, tweet_mode = "extended", lang = "en")

# print last 10 tweets from this account
print("Show recent 10 tweets: \n")
for i,tweet in enumerate(tweets[0:11], 1):
  print(str(i) + ". " + tweet.full_text + "\n")
# Dataframe for tweets
df = pd.DataFrame([tweet.full_text for tweet in tweets], columns = ["Posted Tweets"])

# first 5 tweets in dataframe
df.head()
# Text cleaning

def clean_text(text):
  text = re.sub(r'#', '', text)
  text = re.sub(r'@[A-Za-z0-9]+', '', text)
  text = re.sub(r'RT[\s]+','', text)
  text = re.sub(r':', '', text)
  text = re.sub(r'_', '', text)
  text = re.sub(r'&amp', '', text)
  text = re.sub(r'https:?\/\/\S+', '', text)
  
  return text

df['Posted Tweets'] = df['Posted Tweets'].apply(clean_text)
df = df.astype(str).apply(lambda x: x.str.encode('ascii', 'ignore').str.decode('ascii'))
df

# subjectivity function
def subjectivity(text):
  return TextBlob(text).sentiment.subjectivity

# Polarity Function:
def polarity(text):
  return TextBlob(text).sentiment.polarity

# Subjectivity and Polarity Columns
df['Subjectivity'] = df['Posted Tweets'].apply(subjectivity)
df['Polarity'] = df['Posted Tweets'].apply(polarity)

# New dataframe with subjectivity and polarity
df
# Word cloud

words = ' '.join([twts for twts in df['Posted Tweets']])
wordcloud = WordCloud(width = 600, height = 350, random_state = 21, max_font_size = 119).generate(words)

plt.imshow(wordcloud, interpolation = 'bilinear')
plt.axis('off')
plt.show()
# negative, neutral and positive analysis

def analysis(score):
  if score < 0:
    return 'Negative'
  elif score == 0:
    return 'Neutral'
  else:
    return 'Positive'

df['Analysis'] = df['Polarity'].apply(analysis)
df
# print positive tweets
j=1
sortedDF= df.sort_values(by=['Polarity'])

for i in range(0, sortedDF.shape[0]):
  if (sortedDF['Analysis'][i] == 'Positive'):
    print(str(j)+ '. ' +sortedDF['Posted Tweets'][i])
    print()
    j = j+1
# negative tweets
j = 1
sortedDF = df.sort_values(by=['Polarity'], ascending = 'False')

for i in range(0, sortedDF.shape[0]):
  if (sortedDF['Analysis'][i] == 'Negative'):
    print(str(j)+ '. ' +sortedDF['Posted Tweets'][i])
    print()
    j = j + 1
# Plot polarity and subjectivity

plt.figure(figsize= (8,6))
for i in range(0,df.shape[0]):
  plt.scatter(df['Polarity'][i], df['Subjectivity'][i], color= 'Orange')

plt.title('Sentiment Analysis')
plt.xlabel('Polarity')
plt.ylabel('Subjectivity')
plt.show()
# Percentage of positive tweets
positive_tweets = df[df.Analysis == 'Positive']
positive_tweets = positive_tweets['Posted Tweets']

pos = round((positive_tweets.shape[0] / df.shape[0]) * 100 , 1)
pos
# Percentage of negative tweets
negative_tweets = df[df.Analysis == 'Negative']
negative_tweets = negative_tweets['Posted Tweets']

neg = round((negative_tweets.shape[0] / df.shape[0]) * 100 , 1)
neg
# Percentage of neutral tweets
neutral_tweets = df[df.Analysis == 'Neutral']
neutral_tweets = neutral_tweets['Posted Tweets']

neu = round((neutral_tweets.shape[0] / df.shape[0]) * 100 , 1)
neu
# Visualization of positive, neutral and negative tweet (in percentage)
labels = ['Positive', 'Neutral', 'Negative']
sizes = [pos, neu, neg]
colors = ['#f3c190','#f29d4a', '#f37d0c']
explode = (0.05,0.05,0.05)
 
plt.pie(sizes, explode = explode, colors = colors, labels=labels, autopct='%1.1f%%', startangle=90, pctdistance=0.81)


centre_circle = plt.Circle((0,0),0.60,fc='white')
fig = plt.gcf()
fig.gca().add_artist(centre_circle)

plt.tight_layout()
plt.title('Sentiment Analysis of Tweets')
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.16177444272787464, 'fraction_numerical': 0.021187375855219598, 'mean_word_length': 5.383098591549296, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '422709', 'license': 'MIT', 'n_tokens_mistral': 1743, 'n_tokens_neox': 1623, 'n_words': 400, 'path': 'sentiment_analysis.ipynb', 'repo_name': 'Gayatri-B/Sentiment-Analysis', 'size': '4531'}