Pythonはメールヘッダの基本情報を抽出する

2262 ワード

1メール内容
現在のメールの名前を「1.txt」とし、メールの内容は次のようにします.
From:   [email protected] on behalf of Bieber
Leader [[email protected]]
Sent:   2017-07-01 12:48
To: '[email protected]'; [email protected];
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つの抽出関数を用いて,4つのキーワードを配列に入れ,正則で抽出する.
  • の4つの情報はすべてグローバル関数を行い、一致した場合、グローバル関数+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:   [email protected] on behalf of Bieber
    Leader [[email protected]]
    
    Sent:   2017-07-01 12:48
    
    To: '[email protected]'; [email protected];
    
    Willim Johnson; John Snow
    
    Subject:    The battlefield in Winterfell