def reaction_removed_handler(client, mid, author_id, thread_id, thread_type, ts, msg): global emotionmap global reaction_history if author_id != client.uid: # update emotion map message = client.fetchMessageInfo(mid, thread_id=thread_id) pol = SentimentIntensityAnalyzer().polarity_scores(message.text) try: reaction = reaction_history[(author_id, mid)] except KeyError: # emotion history cleared before reaction removed return react_sentiment = emotionmap[reaction][0] react_sentiment = [ emotionmap[reaction][1] * i for i in react_sentiment ] react_sentiment = [ i - j for i, j in zip(react_sentiment, list(pol.values())[:-1][::-1]) ] emotionmap[reaction][1] -= 1 react_sentiment = [ float(i / emotionmap[reaction][1]) for i in react_sentiment ] emotionmap[reaction][0] = react_sentiment log.info(f"Removed sentiment {pol} for message {mid} to {reaction}.") log.info(emotionmap)
def reaction_added_handler(client, mid, reaction, author_id, thread_id, thread_type): global emotionmap global reaction_history if author_id != client.uid: # add to reaction reaction history reaction_history[(author_id, mid)] = reaction # update emotion map pol = SentimentIntensityAnalyzer().polarity_scores( client.fetchMessageInfo(mid, thread_id=thread_id).text) react_sentiment = emotionmap[reaction][0] react_sentiment = [ emotionmap[reaction][1] * i for i in react_sentiment ] react_sentiment = [ i + j for i, j in zip(react_sentiment, list(pol.values())[:-1][::-1]) ] emotionmap[reaction][1] += 1 react_sentiment = [ float(i / emotionmap[reaction][1]) for i in react_sentiment ] emotionmap[reaction][0] = react_sentiment log.info(f"Added sentiment {pol} for message {mid} to {reaction}.") log.info(emotionmap)
def sentiment_react(client, author_id, message_object, thread_id, thread_type): global emotionmap pol = SentimentIntensityAnalyzer().polarity_scores(message_object.text) compound = pol['compound'] pol = list(pol.values())[:-1][::-1] similarity = { np.dot(pol, emotionmap[i][0]) / (np.linalg.norm(pol) * np.linalg.norm(emotionmap[i][0])): i for i in emotionmap.keys() } # if emotion vector is +/- ~30 degrees from an emotion, send that reaction if sorted(list(similarity.keys()), reverse=True)[0] > 0.866 and np.absolute(compound) > 0.4: action_queue.put( Action(client, 'reaction', thread_id, thread_type, mid=message_object.uid, reaction=similarity[sorted(list(similarity.keys()), reverse=True)[0]]))
def polarity(dataframe, review_column): """ Takes a dataframe and the column name containing text to calculate the sentiment polarity of. Calculates polarity then appends to existing dataframe to return. :params dataframe dataframe: :params review_column string: :returns dataframe: """ # Datatype checks if not isinstance(dataframe, pd.DataFrame): raise ValueError('dataframe is not a pandas dataframe') if not isinstance(review_column, str): raise ValueError('review_column is not a string') if not review_column in dataframe: raise ValueError('review_column is not in the dataframe') dataframe = dataframe.dropna() rows = dataframe.shape[0] scores_array = np.zeros([rows, 4]) keys = [] index_1 = 0 for review in dataframe[review_column]: scores = SentimentIntensityAnalyzer().polarity_scores(review) scores_array[index_1] = list(scores.values()) if index_1 == 0: keys = list(scores.keys()) index_1 += 1 index_2 = 0 for k in keys: dataframe[k] = scores_array[:, index_2] index_2 += 1 return dataframe
def analyze_tweets(): stock_code = pyip.inputStr("Please enter a stock code:$") no_of_tweets = pyip.inputNum("Please enter number of tweets to be parsed:") print("Pulling tweets from twitter....") results = [status._json for status in tweepy.Cursor(api.search, q="$"+stock_code, tweet_mode='extended', lang='en').items(no_of_tweets)] positive_tweet_count = 0 negative_tweet_count = 0 neutral_tweet_count = 0 positive_score = 0 negative_score = 0 neutral_score = 0 tweets = "" tweet_list = [] for result in results: tweet = result["full_text"] tweets += tweet tweet_list.append(tweet) print(tweet) score = SentimentIntensityAnalyzer().polarity_scores(tweet) # access the corresponding score from the result of SentimentIntensityAnalyzer pos = score['pos'] neg = score['neg'] neu = score['neu'] # determine which polarity of tweet is it by taking the max argument max_score = max(score.values()) print(max_score) print('*' * 10) # now get the index to be used for comparison to classify which kind of tweet is it if pos > neg: positive_tweet_count += 1 elif neg > pos: negative_tweet_count += 1 elif neg == pos: neutral_tweet_count += 1 print("*" * 20) print(f"Number of positive tweets: {positive_tweet_count} ({percentage(positive_tweet_count, no_of_tweets)}%)") print(f"Number of negative tweets: {negative_tweet_count} ({percentage(negative_tweet_count, no_of_tweets)}%)") print(f"Number of neutral tweets: {neutral_tweet_count} ({percentage(neutral_tweet_count, no_of_tweets)}%)") counts = [positive_tweet_count, negative_tweet_count, negative_tweet_count] plt.style.use('seaborn') colors = ['#ff9999','#66b3ff','#99ff99'] fig, ax, = plt.subplots() explode = (0.1, 0.1, 0.1) ax.axis('equal') ax.pie(counts, explode=explode, labels=["positive", "negative", "neutral"], autopct='%1.1f%%', shadow=True, startangle=90, colors=colors ) plt.show()