1

I've watched and rewatched the lecture and walkthroughs on pset6 analyze.py, and read the tokenizer documentation. Here's my code. Can someone help me figure out what I'm doing wrong?

import nltk

class Analyzer():
"""Implements sentiment analysis."""

    def __init__(self, positives, negatives):
        """Initialize Analyzer."""

        # TODO
        self.positives = set()
        self.negatives = set()

        file = open(positives, "r")

        for line in file:
            if not line.startswith((";", " ")):
                self.positives.add(line.strip("\n"))
        file.close()

        file2 = open(negatives, "r")

        for line in file:
            if not line.startswith((";", " ")):
                self.negatives.add(line.strip("\n"))
        file2.close()

    def analyze(self, text):
        """Analyze text for sentiment, returning its score."""

        # TODO

        self.tokenizer = nltk.tokenize.TweetTokenizer()
        tokens = self.tokenizer.tokenize(text)

        i = 0

        with open(self.positives) as lines:
            for line in lines:
                for token in tokens:
                    if token.lower() == line:
                        i = i + i

        with open(self.negatives) as lines:
            for line in lines:
                for token in tokens:
                    if token.lower() == line:
                        i = i - 1

        if i > 0:
            return 1
        elif i < 0:
            return -1
        else:
            return 0
3

Why do you use open with self.positives? As self.positives is a set, you could simply use if token in self.positives: or maybe if token.lower() in self.positives:

Also, return the score, not just -1, 0, or 1.

1
  • THANK YOU!!!!!! Yes, so obvious. I was trying too literally to follow the walkthrough directions. Thank you again!!
    – Scott
    Mar 14 '17 at 12:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .