我正在使用此函数来解析电子邮件。我能够解析“简单”的多部分电子邮件,但当电子邮件定义多个边界(子部分)时,它会产生错误(UnboundLocalError:分配前引用的局部变量“html”)。我希望脚本将文本和 html 部分分开并仅返回 html 部分(除非没有 html 部分,否则返回文本)。
def get_text(msg):
text = ""
if msg.is_multipart():
for part in msg.get_payload():
if part.get_content_charset() is None:
charset = chardet.detect(str(part))['encoding']
else:
charset = part.get_content_charset()
if part.get_content_type() == 'text/plain':
text = unicode(part.get_payload(decode=True),str(charset),"ignore").encode('utf8','replace')
if part.get_content_type() == 'text/html':
html = unicode(part.get_payload(decode=True),str(charset),"ignore").encode('utf8','replace')
if html is None:
return text.strip()
else:
return html.strip()
else:
text = unicode(msg.get_payload(decode=True),msg.get_content_charset(),'ignore').encode('utf8','replace')
return text.strip()
最佳答案
就像评论说的那样,您总是检查 html 但仅在其中一种特定情况下声明它。这就是错误告诉你的,你在分配它之前引用了 html。在 python 中,如果某物尚未分配给任何东西,则检查它是否为 None 是无效的。例如打开python交互提示符:
>>> if y is None:
... print 'none'
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined
如您所见,您不能仅仅通过检查 none 来查看变量是否存在。回到您的具体案例。
您需要先将 html 设置为 None,然后稍后您将检查它是否仍然是 None。即像这样编辑您的代码:
def get_text(msg):
text = ""
if msg.is_multipart():
html = None
for part in msg.get_payload():
if part.get_content_charset() is None:
charset = chardet.detect(str(part))['encoding']
else:
charset = part.get_content_charset()
if part.get_content_type() == 'text/plain':
text = unicode(part.get_payload(decode=True),str(charset),"ignore").encode('utf8','replace')
if part.get_content_type() == 'text/html':
html = unicode(part.get_payload(decode=True),str(charset),"ignore").encode('utf8','replace')
if html is None:
return text.strip()
else:
return html.strip()
else:
text = unicode(msg.get_payload(decode=True),msg.get_content_charset(),'ignore').encode('utf8','replace')
return text.strip()
这解释了更多: http://code.activestate.com/recipes/59892-testing-if-a-variable-is-defined/
关于python - 使用 Python 解析包含子部分的多部分电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4824376/