For some reason when i run the following python code I get the following error:
Traceback (most recent call last): File "/home/ubuntu/workspace/pset6/sentiments/analyzer.py", line 20, in init positives[h] = line.strip(' ') # store word and hash code in dictionary TypeError: 'str' object does not support item assignment
What I want to do is store the line after it has been read in my dictionary along with its hashcode.
This is so I can access the word later on using the hashcode. A hash table essentially.
The problem seems to be here:
positives[h] = line.strip(' ')
I have no idea why that would not work.
Any help would be appreciated. Thanks
import nltk
class Analyzer():
"""Implements sentiment analysis."""
# create two new dictionaries to store positive and negative words in memory
positives = {}
negatives = {}
def __init__(self, positives, negatives):
"""Initialize Analyzer."""
# open positive-words.txt and read line by line, hashing each line and storing the hash and word in the appropriate dictionary
with open(positives, "r") as lines:
for line in lines:
if line.startswith(';'): # ignore comments at top of text file
continue
else:
h = hash(line.strip(' ')) # hash word using built in python hash function, removing any spaces
positives[h] = line.strip(' ') # store word and hash code in dictionary
# open negative-words.txt and read line by line, hashing each line and storing the hash and word in the appropriate dictionary
with open(negatives, "r") as lines:
for line in lines:
if line.startswith(';'):
continue
else:
h = hash(line.strip(' '))
negatives[h] = line.strip(' ')
def analyze(self, text):
"""Analyze text for sentiment, returning its score."""
score = 0
for word in text.split():
h = hash(word.strip(' '))
if positives[h] == word.strip(' '):
score += 1
elif negatives[h] == word.strip(' '):
score -= 1
else:
continue
return score