Skip to content

Instantly share code, notes, and snippets.

@timo-boehm
Last active March 18, 2019 14:52
Show Gist options
  • Save timo-boehm/598e9f7ae5231f889a197af96be48787 to your computer and use it in GitHub Desktop.
Save timo-boehm/598e9f7ae5231f889a197af96be48787 to your computer and use it in GitHub Desktop.
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