gpt4 book ai didi

python - Python : SyntaxError

转载 作者:行者123 更新时间:2023-12-03 08:23:26 27 4
gpt4 key购买 nike

我正在编写用于解析电子邮件的脚本,但是以下部分的for循环上有一些SyntaxError:

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 "/IS/extraction.py", line 52

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

最佳答案

您正在尚未支持dict理解的旧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()))

关于python - Python : SyntaxError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19457184/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com