我正在尝试运行下面的代码,当我运行python tfidf.py
(Python 2.6.9)时,我在下面的行中出现SyntaxError: invalid syntax
错误,指向for语句。我做错了什么?
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)
答案 0 :(得分:5)
这不是一个声明,这是一个词典理解。这只是在2.7中引入的。生成一个可迭代的2元组,并将其传递给dict()
构造函数。
答案 1 :(得分:1)
a = [3, 2, 1, 0]
d = {i: a[i] for i in a} # python > 2.6
e = dict((i, a[i]) for i in a) # python <= 2.6
print e == d