0

I've checked over my code many times for errors, but everything looks logically sound to me. For some reason, "counter" in the analyze method will never change, which means that my conditional statements are not working properly. I don't see anything wrong with them though... I'd appreciate any help in finding the problem, either with my implementation of my two sets or my conditionals...

import nltk

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

    def __init__(self, positives, negatives):
        """Initialize Analyzer."""
        self.positives = set()
        self.negatives = set()
        with open("positive-words.txt", "r") as file_pos:
            for line in file_pos:
                if line.startswith(";") == False:
                    self.positives.add(line.strip)
        with open("negative-words.txt", "r") as file_neg: 
            for line in file_neg:
                if line.startswith(";") == False:
                    self.negatives.add(line.strip)
        file_pos.close()
        file_neg.close()

    def analyze(self, text):
        """Analyze text for sentiment, returning its score."""
        score = 0
        tokenizer = nltk.tokenize.TweetTokenizer()
        tokens = tokenizer.tokenize(text)
        for token in tokens:
            if token.lower() in self.positives == True:
                score = score + 1
            elif token.lower() in self.negatives == True:
                score = score - 1
        print(score)
        return score
1

One problem is here self.positives.add(line.strip). line.strip returns the method whereas line.strip() returns the result of the method. (Ditto negatives).

You could do a quick test in command-line python to see the difference.

Python 3.4.3 (default, Jul 28 2015, 18:20:59) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> line = " word "
>>> line.strip
<built-in method strip of str object at 0x7f15ac306dc0>
>>> line.strip()
'word'
>>> 
| improve this answer | |
  • I fixed the mentioned issue, but my conditionals are still not entered. Do you notice any other problem? – Jason_V Jul 7 '17 at 15:57
  • 1
    I think this syntax if token.lower() in self.positives == True: is wrong. try it with if token.lower() in self.positives. Also, if (token.lower() in self.positives) == True: would work. I don't remember the evaluation rule(s) that makes this so. – DinoCoderSaurus Jul 7 '17 at 16:30
  • Thanks so much! I fixed this line as you said and it works perfectly now. Thanks again! – Jason_V Jul 7 '17 at 16:57

You must log in to answer this question.

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