2016-05-02 8 views
3

私はPythonを使用してEnron電子メールデータセットを読み取ります。私はテキストファイルの電子メールを持っています。私はテキストファイルを読んで、各電子メールの "Body"セクションだけを抽出したいと思います。私はFROMTOBCCattachmentsDATEなどについては心配していません。私はBODYセクションのみを希望し、それをリストに保存したいと思います。私はget_payload()機能を使用しようとしましたが、それでもすべてを印刷します。他のコンテンツをスキップしてBodyセクションのみを使用するにはどうすればよいですか?Pythonを使用して電子メールの本文のみを抽出しています

import email.parser 
from email.parser import Parser 

# Code to extract a particular section from raw emails. 

parser = Parser() 
text1 = open("path of the file", "r").read() 
msg = email.message_from_string(text1) 
email = parser.parsestr(text1) 

if msg.is_multipart(): 
    for payload in msg.get_payload(): 
     print payload.get_payload() 
else: 
    print msg.get_payload() 

1つのファイルに複数のメールが含まれる場合があります。サンプルメール。すべてのファイルを仮定し

docID: 1 
segmentNumber: 0 
Body: I just checked with Carolyn on your invoicing for the conference. She 
verified the 85K was processed. 

########################################################## 
docID: 2 
segmentNumber: 0 
Body: null 
########################################################## 
docID: 3 
segmentNumber: 0 
Body: In regard to the costs for the GAM conference, Karen told me the $ 6,695.97 
figure was inclusive of all the items for the conference. However, after 
speaking with Shweta, I found out this is not the case. The CDs are not 
included in this figure. 

The CD cost will be $2,011.50 + the cost of postage/handling (which is 
currently being tabulated). 


########################################################## 
docID: 3 
segmentNumber: 1 
Body: 
This is the original quote for this project and it did not include the 
postage. As soon as I have the details from the vendor, I'll forward those to 
you. 
Please call me if you have any questions. 
+0

をうーん、何を示していることは、電子メール形式で** **はない...電子メールで、ヘッダー名で始まり、次に空白行で始まり、次は本文です。特に、* Body = *や* Body:*のようなものはありません。これは特定の形式なので、電子メールモジュールを使用しないで直接解析するべきです。 –

答えて

0

はあなたの例で指定された形式を持っている、これはうまくいくかもしれない:

email_body_list = [ email.split('Body:')[-1] for email in file_content.split('##########################################################')] 
+0

更新いただきありがとうございます。しかし、これは私が異なる電子メールを区別することはできません。いったんemail_body_listを取得すると、この変数の電子メールの本文セクションにテキストが含まれています。しかし、今私はこれから電子メールを抽出したいのですが?これは私にそれをさせません。右?それをどうすれば解決できますか? –

+0

あなたの最初の質問は、リスト内の電子メールの本文だけを抽出する方法でした。これはその問題を解決します。メール全体をリストに保存しますか? – sc3w

+0

はい、私はむしろ、各電子メールをリストに保存したいと思います。そのため、処理後の特定のメールを後で取り出すことができるようになりました。しかし、以前のアップデートをありがとう。それはデータをまとめています。 –

関連する問題