Skip to content

Instantly share code, notes, and snippets.

@oliver-batey
Last active November 28, 2021 19:59
Show Gist options
  • Save oliver-batey/e32c1977db57bf6cfc1b20d2eb2ed46d to your computer and use it in GitHub Desktop.
Save oliver-batey/e32c1977db57bf6cfc1b20d2eb2ed46d to your computer and use it in GitHub Desktop.
Mean sentence sentiment
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from textblob import TextBlob
def sentiment_polarity(string: str) -> float:
polarity = TextBlob(string).sentiment[0]
return polarity
# Load svo patterns and sentences
svo_data = pd.read_csv("svo_data.csv", index_col=0)
sen_data = pd.read_csv("sentence_data.csv", index_col=0)
# Apply sentiment(score) to the sentence column
sen_data["sentiment_polarity"] = sen_data.sentence.apply(sentiment_polarity)
# Print mean sentiment polarity score
mean_sentiment_scores = sen_data.groupby("keyterm").mean()
# Plot results
labels = [l.replace(" ", "\n") for l in mean_sentiment_scores.index.to_list()]
pos = np.arange(len(labels))
ax = mean_sentiment_scores.plot(
kind="bar", color="lightblue", edgecolor="midnightblue", legend=False, rot=0
)
plt.axhline(0, 0, 1, linestyle="--", color="grey", lw=0.5)
ax.set_xticks(pos)
ax.set_xticklabels(labels)
plt.ylabel("Mean Sentiment Polarity")
plt.tight_layout()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment