我正在创建一个基本的系统,允许用户通过电子邮件回复网站上的一个线程。然而,大多数电子邮件客户端在回复邮件中都包含了以前的电子邮件的文本。这篇文章在网站上是不需要的。
有没有一种可靠的方法,我可以只提取新的信息,而不事先知道之前的电子邮件?我正在使用Python的email类。
示例消息:
Content-Type: text/plain; charset=ISO-8859-1
test message! This is the part I want.
On Thu, Mar 24, 2011 at 3:51 PM, <test@test.com> wrote:
> Hi!
>
> Herman just posted a comment on the website:
>
>
> From: Herman
> "Hi there! I might be interested"
>
>
> Regards,
> The Website Team
> http://www.test.com
>这是来自gmail的回复消息,我相信其他客户可能会有不同的做法。一个好的开始可能是忽略以>开头的行,但在新消息之间也可能有类似的行,然后可能应该保留它们。我还将保留内容类型行和日期行。
发布于 2011-03-24 14:12:18
电子邮件回复的格式取决于客户端。没有任何可行的方法来提取最新的信息,而不存在删除太多或不够的风险。
然而,标记引号的一种常见方法是在引号前加上>,以便以该字符开头的行(特别是在电子邮件的末尾或开头有多个字符)可能是引号。
但是您的示例中的On Thu, Mar 24, 2011 at 3:51 PM, <test@test.com> wrote:很难提取。在引号之前以:结尾的行可能表示它属于引号,您无法确定这一点--它也可能是新消息的一部分,冒号只是一个错误的. (在德国键盘上,: is SHIFT+.)。
发布于 2018-03-05 09:53:34
我觉得这应该管用
import re
string_list = re.findall(r"\w+\s+\w+[,]\s+\w+\s+\d+[,]\s+\d+\s+\w+\s+\d+[:]\d+\s+\w+.*", strings) # regex for On Thu, Mar 24, 2011 at 3:51 PM
res = strings.split(string_list[0]) # split on that match
print(res[0]) # get before string of the regex发布于 2018-07-18 13:42:30
只有在找到匹配时,@LAMRIN TAWSRAS给出的答案才能用于在Gmail日期表达式之前解析文本,否则会引发错误。此外,不需要搜索整个消息中的多个日期表达式,只需找到第一个。因此,我将改进他的解决方案以使用re.search()。
def get_body_before_gmail_reply_date(msg):
body_before_gmail_reply = msg
# regex for date format like "On Thu, Mar 24, 2011 at 3:51 PM"
matching_string_obj = re.search(r"\w+\s+\w+[,]\s+\w+\s+\d+[,]\s+\d+\s+\w+\s+\d+[:]\d+\s+\w+.*", msg)
if matching_string_obj:
# split on that match, group() returns full matched string
body_before_gmail_reply_list = msg.split(matching_string_obj.group())
# string before the regex match, so the body of the email
body_before_gmail_reply = body_before_gmail_reply_list[0]
return body_before_gmail_replyhttps://stackoverflow.com/questions/5420402
复制相似问题