Python 将 session 与字符串电子邮件消息线程分开

标签 python email

我想将回复和转发从一连串的电子邮件中分离到对话中。

一个例子是这样的:

2013 年 7 月 31 日下午 5:15,John Doe 写道:

> example email text
>
>
> *From:* Me [mailto:me@gmail.com]
> *Sent:* Thursday, May 31, 2012 3:54 PM
> *To:* John Doe
> *Subject:* RE: subject
>
> example email text
>
>> Dear David,
>> 
>> Greetings from Doha!
>> Kindly enlighten me. I am confused.
>> 
>> With regards,
>> Smith
>>
>>> Dear Smith,
>>>
>>> Happy New year!
>>> Love
>>>
>>>> Dear Mr Wong,
>>>> Greetings!
>>>> Yours,
>>>> O

上面的例子纯属编造,但格式很真实。一些电子邮件包含多个对话。

我试过了https://github.com/zapier/email-reply-parser和其他包,但不幸的是,由于性能不稳定,它们无法投入生产。

模式很清晰,可以通过数“>”的个数来分隔对话。我最初的想法是遍历整个文档,找出有多少个“>”,然后将每个“>”“>>”“>>>”和“>>>>”提取为每个对话。

我想知道有没有更好的出路?

非常感谢!

最佳答案

这是一个非常简单的解决方案 itertools.groupby假设电子邮件正文不包含 '>' :

In [165]: for _, v in itertools.groupby(text.splitlines(), key=lambda x: x.count('>')):
     ...:     print('\n'.join(v))
     ...:     print('-' * 20)
     ...:     

groupby为你计数。您需要类似于 key=lambda x: len(re.match(r'\>+', x).group(0)) 的内容以获得更彻底的解决方案。

输出:

> example email text
>
>
> *From:* Me [mailto:me@gmail.com]
> *Sent:* Thursday, May 31, 2012 3:54 PM
> *To:* John Doe
> *Subject:* RE: subject
>
> example email text
>
--------------------
>> Dear David,
>> 
>> Greetings from Doha!
>> Kindly enlighten me. I am confused.
>> 
>> With regards,
>> Smith
>>
--------------------
>>> Dear Smith,
>>>
>>> Happy New year!
>>> Love
>>>
--------------------
>>>> Dear Mr Wong,
>>>> Greetings!
>>>> Yours,
>>>> O
--------------------

关于Python 将 session 与字符串电子邮件消息线程分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45183903/

相关文章:

Python pandas - 根据groupby选择行

c++ - Qt编程: More productive in Python or C++?

Python pytz : timezone ("xxx") gives "unpack requires a string argument of length 44"

python - 使用offlineimap时出错 : getfolder() asked for nonexisting folder

python - django-allauth 验证电子邮件通过 example.com 发送 :port

Python无法登录Robot框架log.html

ruby-on-rails-3 - Ruby on Rails with Sorcery 重置密码电子邮件出现未定义方法错误

php - 如何使用带有PHP邮件功能的TCPDF

php - Codeigniter achor 在电子邮件收件箱中生成狡猾的链接..可能是什么问题?

email - 如何将Zend_Mail_Transport_Smtp与托管的Google Apps结合使用?