Python: SyntaxError

2019-03-06 01:08发布

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

Please help me out of this!

EDIT:

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

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

1条回答
一夜七次
2楼-- · 2019-03-06 01:32

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

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()))
查看更多
登录 后发表回答