您在不支持字典推导的旧 Python 版本上运行它。该{key: value for ... in ...}
语法仅在 Python 2.7 和更新版本中可用:
Python 2.6.8 (unknown, May 22 2013, 11:58:55)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def main():
... writer = csv.DictWriter(open('features.csv', 'w'), list(EXTRACTS.keys()))
... for mail in os.listdir(MAILDIR):
... writer.writerow({
... key: value(email.message_from_file(open(os.path.join(MAILDIR, mail), 'r')))
... for key, value in EXTRACTS.items()
File "<stdin>", line 6
for key, value in EXTRACTS.items()
^
SyntaxError: invalid syntax
用字典构造函数和生成器表达式替换该行:
writer.writerow(dict(
(key, value(email.message_from_file(open(os.path.join(MAILDIR, mail), 'r'))))
for key, value in EXTRACTS.items()
))
但是,您确实希望避免阅读每个关键项对的电子邮件EXTRACTS
;每个外循环读取一次:
def main():
writer = csv.DictWriter(open('features.csv', 'w'), list(EXTRACTS.keys()))
for mail in os.listdir(MAILDIR):
mail = email.message_from_file(open(os.path.join(MAILDIR, mail), 'r'))
writer.writerow(dict((key, value(mail)) for key, value in EXTRACTS.items()))