使用python处理文本文件时的预期字符串或缓冲区

时间:2013-02-26 03:48:37

标签: 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.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

我在其他(较小的)文件上运行代码,所以我猜这个问题是我的文件。该文件似乎只是一堆文本。有人能指出我的写入方向进行调试吗?

2 个答案:

答案 0 :(得分:0)

只能有一个from地址(我想!):

以下内容:

from_address = PAT_EMAIL.findall(email["from"]) 

我觉得您正在尝试复制email.message_from_fileemail.utils.parseaddr

的作品
from email.utils import parseaddr

>>> s = "Jon Clements <jon@example.com>"
>>> from email.utils import parseaddr
>>> parseaddr(s)
('Jon Clements', 'jon@example.com')

因此,您可以使用parseaddr(email['from'])[1]获取电子邮件地址并使用该地址。

同样,您可能希望查看email.utils.getaddresses来处理tocc地址......

答案 1 :(得分:0)

好吧,我没有解决这个问题,但为了我自己的目的已经解决了这个问题。我插入了一个try语句,以便迭代继续经过任何TypeError。对于每千个电子邮件地址,我将获得大约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