5

我有一个抄送标题字段的纯文本,如下所示:

friend@email.com, John Smith <john.smith@email.com>,"Smith, Jane" <jane.smith@uconn.edu>

是否有任何经过实战测试的模块可以正确解析它?

(如果它在 python 中,则奖励!电子邮件模块只返回原始文本,没有任何拆分它的方法,AFAIK)(如果它将名称和地址拆分为字段,则也是奖励)

4

4 回答 4

17

有一堆函数可用作标准 python 模块,但我认为您正在寻找 email.utils.parseaddr()email.utils.getaddresses()

>>> addresses = 'friend@email.com, John Smith <john.smith@email.com>,"Smith, Jane" <jane.smith@uconn.edu>'
>>> email.utils.getaddresses([addresses])
[('', 'friend@email.com'), ('John Smith', 'john.smith@email.com'), ('Smith, Jane', 'jane.smith@uconn.edu')]
于 2011-03-24T23:35:01.887 回答
0

我自己没有使用过它,但在我看来你可以很容易地使用csv包来解析数据。

于 2011-03-24T23:34:20.743 回答
0

波纹管是完全没有必要的。我在意识到你可以传递getaddresses()一个包含多个地址的单个字符串的列表之前写了它。

我没有机会查看电子邮件标头中地址的规范,但是根据您提供的字符串,此代码应该可以将其拆分为列表,如果逗号在引号内,请确保忽略逗号(和因此是名称的一部分)。

from email.utils import getaddresses

addrstring = ',friend@email.com, John Smith <john.smith@email.com>,"Smith, Jane" <jane.smith@uconn.edu>,'

def addrparser(addrstring):
    addrlist = ['']
    quoted = False

    # ignore comma at beginning or end
    addrstring = addrstring.strip(',')

    for char in addrstring:
        if char == '"':
            # toggle quoted mode
            quoted = not quoted
            addrlist[-1] += char
        # a comma outside of quotes means a new address
        elif char == ',' and not quoted:
            addrlist.append('')
        # anything else is the next letter of the current address
        else:
            addrlist[-1] += char

    return getaddresses(addrlist)

print addrparser(addrstring)

给出:

[('', 'friend@email.com'), ('John Smith', 'john.smith@email.com'),
 ('Smith, Jane', 'jane.smith@uconn.edu')]

我很想看看其他人会如何解决这个问题!

于 2011-03-25T02:58:58.577 回答
0

将多个电子邮件字符串转换为字典(将多个电子邮件名称转换为一个字符串)。

emailstring = 'Friends <friend@email.com>, John Smith <john.smith@email.com>,"Smith" <jane.smith@uconn.edu>'

用逗号分割字符串

email_list = emailstring.split(',')

名称是关键,电子邮件是价值并制作字典。

email_dict = dict(map(lambda x: email.utils.parseaddr(x), email_list))

结果如下:

{'John Smith': 'john.smith@email.com', 'Friends': 'friend@email.com', 'Smith': 'jane.smith@uconn.edu'}

笔记:

如果有相同的名称但不同的电子邮件 ID,则跳过一条记录。

'Friends <friend@email.com>, John Smith <john.smith@email.com>,"Smith" <jane.smith@uconn.edu>, Friends <friend_co@email.com>'

“朋友”重复了 2 次。

于 2015-07-21T07:28:21.733 回答