Created
August 1, 2020 14:45
-
-
Save sayanmondal2098/7ca3f2e7c516202399434c759fcd58ef to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Twitter Sentiment Analysis | |
import sys | |
import csv | |
import tweepy | |
import matplotlib.pyplot as plt | |
from collections import Counter | |
if sys.version_info[0] < 3: | |
input = raw_input | |
## Twitter credentials | |
consumer_key = "------------" | |
consumer_secret = "------------" | |
access_token = "----------" | |
access_token_secret = "-----------" | |
## set up an instance of Tweepy | |
auth = tweepy.OAuthHandler(consumer_key, consumer_secret) | |
auth.set_access_token(access_token, access_token_secret) | |
api = tweepy.API(auth) | |
## set up an instance of the AYLIEN Text API | |
client = textapi.Client(application_id, application_key) | |
## search Twitter for something that interests you | |
query = input("What subject do you want to analyze for this example? \n") | |
number = input("How many Tweets do you want to analyze? \n") | |
results = api.search( | |
lang="en", | |
q=query + " -rt", | |
count=number, | |
result_type="recent" | |
) | |
print("--- Gathered Tweets \n") | |
## open a csv file to store the Tweets and their sentiment | |
file_name = 'Sentiment_Analysis_of_{}_Tweets_About_{}.csv'.format(number, query) | |
with open(file_name, 'w', newline='') as csvfile: | |
csv_writer = csv.DictWriter( | |
f=csvfile, | |
fieldnames=["Tweet", "Sentiment"] | |
) | |
csv_writer.writeheader() | |
print("--- Opened a CSV file to store the results of your sentiment analysis... \n") | |
## tidy up the Tweets and send each to the AYLIEN Text API | |
for c, result in enumerate(results, start=1): | |
tweet = result.text | |
tidy_tweet = tweet.strip().encode('ascii', 'ignore') | |
if len(tweet) == 0: | |
print('Empty Tweet') | |
continue | |
response = client.Sentiment({'text': tidy_tweet}) | |
csv_writer.writerow({ | |
'Tweet': response['text'], | |
'Sentiment': response['polarity'] | |
}) | |
print("Analyzed Tweet {}".format(c)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment