Python: SyntaxError

后端 未结 1 352
青春惊慌失措
青春惊慌失措 2021-01-28 22:24

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.DictWrite         


        
相关标签:
1条回答
  • 2021-01-28 22:51

    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()))
    
    0 讨论(0)
提交回复
热议问题