Last active
March 27, 2020 19:35
-
-
Save iamscotttaylor/e1897161e2545074e15273a7114ca4f1 to your computer and use it in GitHub Desktop.
Sentiment Analysis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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