Skip to content

Instantly share code, notes, and snippets.

@timo-boehm
Last active Mar 18, 2019
Embed
What would you like to do?
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