Twitter Sentiment Analysis
I have long dreamt of exploring human behaviour with technology. Thanks to Artificial Intelligence this dream was turned into a reality- I developed an algorithm via which I could conduct Sentiment Analysis using the Twitter API to fetch tweets to act as a dataset. This code required me to read a number of journals and research papers such that the code is succinct and seamless. Following is the code:
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import twitter_credentials # Source document name #
class TwitterStreamer():
def __init__(self):
pass
def stream_tweets(self, fetched_tweets_filename, hash_tag_list):
listener = StdOutListener(fetched_tweets_filename)
auth = OAuthHandler(twitter_credentials.CONSUMER_KEY,twitter_credentials.CONSUMER_SECRET)
auth.set_access_token(twitter_credentials.ACCESS_TOKEN,twitter_credentials.ACCESS_TOKEN_SECRET)
stream = Stream(auth, listener)
stream.filter(track=hash_tag_list)
class StdOutListener(StreamListener):
def __init__(self, fetched_tweets_filename):
self.fetched_tweets_filename = fetched_tweets_filename
def on_data(self, data):
try:
print(data)
with open(self.fetched_tweets_filename, 'a') as tf:
tf.write(data)
return True
except BaseException as e:
print("Error on_data %s" % str(e))
return True
def on_error(self, status):
print(status)
if __name__ == '__main__':
hash_tag_list = ["donal trump", "hillary clinton", "barack obama", "bernie sanders"]
fetched_tweets_filename = "tweets.txt"
twitter_streamer = TwitterStreamer()
twitter_streamer.stream_tweets(fetched_tweets_filename, hash_tag_list)
from tweepy import OAuthHandler
from tweepy import Stream
import twitter_credentials # Source document name #
class TwitterStreamer():
def __init__(self):
pass
def stream_tweets(self, fetched_tweets_filename, hash_tag_list):
listener = StdOutListener(fetched_tweets_filename)
auth = OAuthHandler(twitter_credentials.CONSUMER_KEY,twitter_credentials.CONSUMER_SECRET)
auth.set_access_token(twitter_credentials.ACCESS_TOKEN,twitter_credentials.ACCESS_TOKEN_SECRET)
stream = Stream(auth, listener)
stream.filter(track=hash_tag_list)
class StdOutListener(StreamListener):
def __init__(self, fetched_tweets_filename):
self.fetched_tweets_filename = fetched_tweets_filename
def on_data(self, data):
try:
print(data)
with open(self.fetched_tweets_filename, 'a') as tf:
tf.write(data)
return True
except BaseException as e:
print("Error on_data %s" % str(e))
return True
def on_error(self, status):
print(status)
if __name__ == '__main__':
hash_tag_list = ["donal trump", "hillary clinton", "barack obama", "bernie sanders"]
fetched_tweets_filename = "tweets.txt"
twitter_streamer = TwitterStreamer()
twitter_streamer.stream_tweets(fetched_tweets_filename, hash_tag_list)
Hope to conduct more such projects in the future!
Comments
Post a Comment