0

just started this and have quite a bit trouble getting used to python despite having read all the courseware. My code keeps returning a neutral face. What is wrong? Thanks.

import nltk

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

def __init__(self, positives, negatives):
    """Initialize Analyzer."""
    #instantiate analyzer
    #create two sets to hold the words
    self.positives = set()
    self.negatives = set()
    #open each file
    #read each file line by line, removing extra space and comments 
    #for positives
    with open(positives) as pfile:
        for line in pfile:
            if not line.startswith(";"):
                line = line.strip()
                self.positives.add(line)
    #for negatives
    with open(negatives) as nfile:
        for line in nfile:
            if not line.startswith(";"):
                line = line.strip()
                self.negatives.add(line)


def analyze(self, text):
    """Analyze text for sentiment, returning its score."""
    #initialise score as 0
    score = 0
    #tokenize the text with help from nltk
    tokenizer = nltk.tokenize.TweetTokenizer()
    tokens = tokenizer.tokenize(text)
    #make all the words in token lower case 
    for i in range(len(tokens)):
        if tokens[i].lower in self.positives:
            score += 1
    for i in range(len(tokens)):
        if tokens[i].lower in self.negatives:
            score -= 1
    return score
0

Call tokens[i].lower by appending parentheses () => tokens[i].lower()

2
  • Thanks. One more question: How does the python interpreter understand "for line in pfile". How does it know what a line even though it has not been declared before? On the same note, my friend used "for token in tokens" when iterating through the list in the analyze function. How does this work too?
    – joshwong
    Mar 28 '17 at 14:09
  • for X in Y: expects Y to be an iterator or iterable, and assigns the various values to X, one at a time. File objects are iterators, the elements are the lines of the file. Lists and sets are iterables instead, slightly different (iterators keep a state, so you'd have to reset the file position to read it again).
    – Blauelf
    Mar 28 '17 at 15:09

You must log in to answer this question.

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