Last active
March 18, 2019 14:52
Star
You must be signed in to star a gist
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
import re | |
import tweepy | |
from textblob import TextBlob | |
def lambda_function(search_term): | |
# Details for connection | |
auth = tweepy.OAuthHandler(consumer_key="XXXX", | |
consumer_secret="XXXX") | |
auth.set_access_token(key="XXXX", | |
secret="XXXX") | |
# Connect to API and collect results | |
api = tweepy.API(auth) | |
api_output = api.search(q=search_term, count=500) | |
# Prepare tweets for analysis | |
def clean_tweet(tweet): | |
return re.sub("(@[\w]*|(https:[\S]*)|([,.;\\n'\"()]))", "", tweet).strip() | |
tweet_list = [t.text for t in api_output] | |
clean_tweets = [clean_tweet(t) for t in tweet_list] | |
unique_tweets = set(clean_tweets) | |
# Calculate sentiments for all tweets | |
sentiments = [TextBlob(t).sentiment.polarity for t in unique_tweets] | |
# Aggregate sentiments in one dictionary | |
aggregated_sentiments = {"positive": len([s for s in sentiments if s > 0]) / len(sentiments), | |
"neutral": len([s for s in sentiments if s == 0]) / len(sentiments), | |
"negative": len([s for s in sentiments if s < 0]) / len(sentiments)} | |
return aggregated_sentiments |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment