Skip to content

Instantly share code, notes, and snippets.

@iamscotttaylor
Last active March 27, 2020 19:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamscotttaylor/e1897161e2545074e15273a7114ca4f1 to your computer and use it in GitHub Desktop.
Save iamscotttaylor/e1897161e2545074e15273a7114ca4f1 to your computer and use it in GitHub Desktop.
Sentiment Analysis
import string
from collections import Counter
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import matplotlib.pyplot as plt
text = open('read.txt', encoding='utf-8').read()
lower_case = text.lower()
cleaned_text = lower_case.translate(str.maketrans('', '', string.punctuation))
tokenized_words = word_tokenize(cleaned_text, 'english')
final_words = []
for word in tokenized_words:
if word not in stopwords.words('english'):
final_words.append(word)
emotion_list = []
with open('emotions.txt', 'r') as file:
for line in file:
clear_line = line.replace('\n', '').replace(',', '').replace("'", '').strip()
word, emotion = clear_line.split(':')
if word in final_words:
emotion_list.append(emotion)
w = Counter(emotion_list)
def sentiment_analyse(sentiment_text):
score = SentimentIntensityAnalyzer().polarity_scores(sentiment_text)
print(score)
neg = score['neg']
pos = score['pos']
if neg > pos:
print("Negative Sentiment")
elif pos > neg:
print("Positive Sentiment")
else:
print("Neutral")
sentiment_analyse(cleaned_text)
fig, ax1 = plt.subplots()
ax1.bar(w.keys(), w.values())
fig.autofmt_xdate()
plt.savefig('graph.png')
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment