#!/usr/bin/env python3
import os
import sys
import helpers
from analyzer import Analyzer
from termcolor import colored
# ensure proper usage
if len(sys.argv) != 2:
sys.exit("Usage: ./tweets @username")
# absolute paths to lists
positives = os.path.join(sys.path[0], "positive-words.txt")
negatives = os.path.join(sys.path[0], "negative-words.txt")
# initialize analyzer
analyzer = Analyzer(positives, negatives)
# set screen_name
screen_name = sys.argv[1]
# queries Twitter's API for user's most recent 50 tweets
tweets = helpers.get_user_timeline(screen_name, 50)
# if screen_name doesn't exist, return error
if tweets == None:
sys.exit("User is private or doesn't exist")
# if screen_name exist, analyze each tweet and output it
for tweet in tweets:
score = analyzer.analyze(tweet)
if score > 0.0:
print(colored("{} {}".format(score, tweet), "green"))
elif score < 0.0:
print(colored("{} {}".format(score, tweet), "red"))
else:
print(colored("{} {}".format(score, tweet), "yellow"))
Here is analyzer:[code hidden]
import nltk
class Analyzer():
"""Implements sentiment analysis."""
def __init__(self, positives, negatives):
"""Initialize Analyzer."""
#load positive and negative words
self.positives = []
with open("positive-words.txt", "r") as pwords:
for line in pwords:
if line.startswith(";") and line.startswith(" "):
pass
else:
self.positives.extend(line.split())
self.negatives = []
with open("negative-words.txt", "r") as nwords:
for line in nwords:
if line.startswith(";") and line.startswith(" "):
pass
else:
self.negatives.extend(line.split())
def analyze(self, text):
"""Analyze text for sentiment, returning its score."""
#assign each word in text a value(-1, 0, 1), calculate texts total score
tokenizer = nltk.tokenize.TweetTokenizer()
tokens = tokenizer.tokenize(text)
score = 0
for token in tokens:
token.lower()
if token in self.positives:
score += 1
elif token in self.negatives:
score -= 1
return score