美文网首页
Python 提取邮件头基本信息

Python 提取邮件头基本信息

作者: Tim_Lee | 来源:发表于2017-07-17 16:17 被阅读0次

1 邮件内容

假设目前邮件名叫“1.txt”,邮件内容为:

From:   Justin-Bieber@entertain.org on behalf of Bieber
Leader [leader@hello.org]
Sent:   2017-07-01 12:48
To: 'staff@hello.org'; custom@hello.org;
Willim Johnson; John Snow
Subject:    The battlefield in Winterfell


I have just met then. More details as soon as possible. So far, so good.

Sent via iPhone 7 plus

2 提取思路

  • 要求把邮件头部信息提取出来,需要提取信息:
    • 发件人(From:)、发件时间(Sent)、收件人(To)、主题(Subject)
  • 初步提取信息所在行的内容即可。
  • 使用一个提取函数,把四个关键词放入数组中,用正则提取。
  • 四个信息都做了全局函数,如果曾经匹配过,则全局函数 + 1,以做标识。
  • 如果一个信息已经匹配过,而下一个信息还没匹配到,这一行的内容也需要读取出来。
  • 提取函数的返回值,如果是 None 则不做处理。
# coding: utf-8
import re

from_count = 0
sent_count = 0
to_count = 0
subject_count = 0


def inspect_string(string):
    global from_count
    global sent_count
    global to_count
    global subject_count

    keyword_list = ['From:', 'Sent:', 'To:', 'Subject:']
    for keyword in keyword_list:
        regex_str = ".*({0}.*)".format(keyword)
        match_obj = re.match(regex_str, string)

        if re.match(".*(From:.*)", string):
            from_count += 1

        if re.match(".*(Sent:.*)", string):
            sent_count += 1

        if re.match(".*(To:.*)", string):
            to_count += 1

        if re.match(".*(Subject:.*)", string):
            subject_count += 1

        if match_obj:
            return match_obj.group(1)

        if from_count > 0 and sent_count < 1:
            return string

        if sent_count > 0 and to_count < 1:
            return string

        if to_count > 0 and subject_count < 1:
            return string


with open('1.txt', 'rb') as f:
    for line in f:
        result = inspect_string(str(line))
        if result is None:
            continue
        print(result)

3 运行结果

From:   Justin-Bieber@entertain.org on behalf of Bieber
Leader [leader@hello.org]

Sent:   2017-07-01 12:48

To: 'staff@hello.org'; custom@hello.org;

Willim Johnson; John Snow

Subject:    The battlefield in Winterfell

相关文章

  • Python 提取邮件头基本信息

    1 邮件内容 假设目前邮件名叫“1.txt”,邮件内容为: 2 提取思路 要求把邮件头部信息提取出来,需要提取信息...

  • 文件类型魔数

    1、从Ultra-edit-32中提取出来的 JPEG (jpg),文件头:FFD8FFPNG (png),文件头...

  • Python——文件编码

    编码的演变 Python编码 python2 Python指定编码 在文件头部增加 -*-coding:utf8-...

  • 各类文件头信息

    [各类文件头信息] 1、从Ultraedit中提取出来的文件头信息,两个字符算一字节(十六进制) JPEG (jp...

  • Vscode 配置为Python IDE

    1.文件头添加 自定义代码片段 文件>首选项>用户代码片段 搜索python 添加代码 添加文件头 新建文件 输入...

  • python学习笔记

    0、文件头 #!/usr/local/python #encoding:utf-8 1、输出 string_1 =...

  • Python中文乱码报错

    Python中文乱码报错 2016.5.31 在Python文件头部加上编码格式: 这样的话应该就没有问题了,主要...

  • pycharm设置python文件模板,自动添加文件头注释

    pycharm设置python文件模板,自动添加文件头注释 背景 每次写python代码的时候,都要手动在文件开头...

  • HELLO

    ### 基本信息 *** 姓名 | 性别 | 出生年月|最后学历| 外语水平| 联系电话| 邮 箱 ---|---...

  • Python 之父抛弃 Python!

    2018.7.13,Python 之父 Guido van Rossum 在 Python 邮件组里发邮称,他将退...

网友评论

      本文标题:Python 提取邮件头基本信息

      本文链接:https://www.haomeiwen.com/subject/htfqkxtx.html