Skip to main content
hid code behind edit link per academic honesty guidelines
Source Link
curiouskiwi
  • 18.7k
  • 2
  • 18
  • 43
#!/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
#!/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:

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

[code hidden]

added 61 characters in body
Source Link

I'm getting this error, I have been working to make it work but i can't. I followed the instructions on setting up the API_KEY value:

I'm getting this error, I have been working to make it work but i can't:

I'm getting this error, I have been working to make it work but i can't. I followed the instructions on setting up the API_KEY value:

Source Link

Error in pset6 API Key not set

I'm getting this error, I have been working to make it work but i can't:

Traceback (most recent call last): File "tweets", line 25, in tweets = helpers.get_user_timeline(screen_name, 50) File "/home/ubuntu/workspace/pset6/sentiments/helpers.py", line 46, in get_user_timeline raise RuntimeError("API_KEY not set") RuntimeError: API_KEY not set

Here is my tweets code:

#!/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:

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