Python:SyntaxError [英] Python: SyntaxError

查看:373
本文介绍了Python:SyntaxError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个脚本来解析电子邮件,但在以下部分的for循环中有一些 SyntaxError

I'm writing a script to parse an email, but there is some SyntaxError on the for loop in the following part:

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()
             })

请帮我出来!

编辑:


文件/IS/extraction.py,第52行

File "/IS/extraction.py", line 52

for key, value in EXTRACTS.items()
  ^ SyntaxError: invalid syntax



推荐答案

您正在旧版本的Python上运行此版本,但尚未支持dict解析。 {key:value for ... in ...} 语法仅适用于Python 2.7及更高版本:

You are running this on an older Python version that doesn't yet support dict comprehensions. The {key: value for ... in ...} syntax is only available in Python 2.7 and newer:

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

用字典构造函数和生成器表达式:

Replace the line with a dictionary constructor and a generator expression:

writer.writerow(dict(
    (key, value(email.message_from_file(open(os.path.join(MAILDIR, mail), 'r'))))
    for key, value in EXTRACTS.items()
))

您确实希望避免阅读 EXTRACTS 中的每个关键项对的电子邮件;阅读它一次每个外层循环:

You do want to avoid reading the email message for every key-item pair in EXTRACTS though; read it once per outer loop:

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()))

这篇关于Python:SyntaxError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆