使用python处理文本文件时需要字符串或缓冲区
我正在从我的thunderbird imap目录中处理一个大的(120mb)文本文件,并试图使用mbox和regex从标题中提取信息。这个过程运行了一段时间,直到我最终得到一个异常:“TypeError:预期的字符串或缓冲区” 此异常引用此代码的第五行:使用python处理文本文件时需要字符串或缓冲区,python,text-processing,Python,Text Processing,我正在从我的thunderbird imap目录中处理一个大的(120mb)文本文件,并试图使用mbox和regex从标题中提取信息。这个过程运行了一段时间,直到我最终得到一个异常:“TypeError:预期的字符串或缓冲区” 此异常引用此代码的第五行: PAT_EMAIL = re.compile(r"[0-9A-Za-z._-]+\@[0-9A-Za-z._-]+") temp_list = [] mymbox = mbox("data.txt") for email in mymbox.v
PAT_EMAIL = re.compile(r"[0-9A-Za-z._-]+\@[0-9A-Za-z._-]+")
temp_list = []
mymbox = mbox("data.txt")
for email in mymbox.values():
from_address = PAT_EMAIL.findall(email["from"])
to_address = PAT_EMAIL.findall(email["to"])
for item in from_address:
temp_list.append(item) #items are added to a temporary list where they are sorted then written to file
我已经在其他(较小的)文件上运行了代码,所以我猜问题出在我的文件上。文件似乎只是一堆文本。有人能告诉我调试这个的写入方向吗?只能有一个
来自地址(我想!):
在以下方面:
from_address = PAT_EMAIL.findall(email["from"])
我有种感觉,你在试图复制和
从email.utils导入parseaddr
>>>s=“Jon Clements”
>>>从email.utils导入parseaddr
>>>解释器
('Jon Clements','jon@example.com')
因此,您可以使用parseaddr(email['from'])[1]
获取电子邮件地址并使用它
类似地,您可能希望查看如何处理到
和抄送
地址…嗯,我没有解决这个问题,但为了自己的目的解决了这个问题。我插入了一个try语句,这样迭代就可以在任何类型错误之后继续进行。对于每一千个电子邮件地址,我得到大约8个失败,这就足够了。谢谢你的意见
PAT_EMAIL = re.compile(r"[0-9A-Za-z._-]+\@[0-9A-Za-z._-]+")
temp_list = []
mymbox = mbox("data.txt")
for email in mymbox.values():
try:
from_address = PAT_EMAIL.findall(email["from"])
except(TypeError):
print "TypeError!"
try:
to_address = PAT_EMAIL.findall(email["to"])
except(TypeError):
print "TypeError!"
for item in from_address:
temp_list.append(item) #items are added to a temporary list where they are sorted then written to file
在迭代失败的地方检查类型(email[“from”])
。你能为你的findall
方法发布代码吗?添加了findall方法来发布。如果满足你的需要,可以用这种方式跳过失败。当然,您可以(尽管我冒着在这里陈述非常明显的风险)使用except部分打印“电子邮件”,找出导致失败的原因,这样您就可以完全避免错误。
PAT_EMAIL = re.compile(r"[0-9A-Za-z._-]+\@[0-9A-Za-z._-]+")
temp_list = []
mymbox = mbox("data.txt")
for email in mymbox.values():
try:
from_address = PAT_EMAIL.findall(email["from"])
except(TypeError):
print "TypeError!"
try:
to_address = PAT_EMAIL.findall(email["to"])
except(TypeError):
print "TypeError!"
for item in from_address:
temp_list.append(item) #items are added to a temporary list where they are sorted then written to file