Arturo Arturo - 7 months ago 15
Python Question

Invalid syntax in Python's for statement

I am trying to run the code below, and when I run

python tfidf.py
(Python 2.6.9) I get
SyntaxError: invalid syntax
error in the line below, pointing to the for statement. What am I doing wrong?

def produceVector(blob, bloblist):
##### SYNTAXERROR: invalid syntax in the "for" in the line below #####
scores = {word: tfidf(word, blob, bloblist) for word in blob.words}
return scores

def tf(word, blob):
return blob.words.count(word) / len(blob.words)

def n_containing(word, bloblist):
return sum(1 for blob in bloblist if word in blob)

def idf(word, bloblist):
return math.log(len(bloblist) / (1 + n_containing(word, bloblist)))

def tfidf(word, blob, bloblist):
return tf(word, blob) * idf(word, bloblist)

Answer

That's not a for statement, that's a dict comprehension. Which was only introduced in 2.7. Generate an iterable of 2-tuples instead and pass it to the dict() constructor.