Python 的 for 语句中的语法无效
Invalid syntax in Python's for statement
我正在尝试 运行 下面的代码,当我 运行 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)
那不是 for 语句,那是听写理解。仅在 2.7 中引入。而是生成一个可迭代的 2 元组并将其传递给 dict()
构造函数。
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
我正在尝试 运行 下面的代码,当我 运行 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)
那不是 for 语句,那是听写理解。仅在 2.7 中引入。而是生成一个可迭代的 2 元组并将其传递给 dict()
构造函数。
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