本月的每月挑戰會主題是NLP,我們會在本文幫你開啟一種可能:使用pandas和python的自然語言工具包分析你Gmail郵箱中的內容。
NLP-風格的項目充滿無限可能:
情感分析是對諸如在線評論、社交媒體等情感內容的測度。舉例來說,關于某個話題的tweets趨向于正面還是負面的意見?一個新聞網站涵蓋的主題,是使用了更正面/負面的詞語,還是經常與某些情緒相關的詞語?這個“正面”的Yelp點評不是很諷刺么?(祝最后去的那位好運!) 分析語言在文學中的使用,進而衡量詞匯或者寫作風格隨時間/地區/作者的變化趨勢. 通過識別所使用的語言的關鍵特征,標記是否為垃圾內容。 基于評論所覆蓋的主題,使用主題抽取進行相似類別的劃分。 通過NLTK's的語料庫,應用Elastisearch和WordNet的組合來衡量Twitter流API上的詞語相似度,進而創建一個更好的實時Twitter搜索。 加入NaNoGenMo項目,用代碼生成自己的小說,你可以從這里大量的創意和資源入手。將Gmail收件箱加載到pandas
讓我們從項目實例開始!首先我們需要一些數據。準備你的Gmail的數據存檔(包括你最近的垃圾郵件和垃圾文件夾)。
https://www.google.com/settings/takeout
現在去散步吧,對于5.1G大小的信箱,我2.8G的存檔需要發送一個多小時。
當你得到數據并為工程配置好本地環境之后好,使用下面的腳本將數據讀入到pandas(強烈建議使用IPython進行數據分析)
from mailbox import mboximport pandas as pd def store_content(message, body=None): if not body: body = message.get_payload(decode=True) if len(message): contents = { "subject": message['subject'] or "", "body": body, "from": message['from'], "to": message['to'], "date": message['date'], "labels": message['X-Gmail-Labels'], "epilogue": message.epilogue, } return df.append(contents, ignore_index=True) # Create an empty DataFrame with the relevant columnsdf = pd.DataFrame( columns=("subject", "body", "from", "to", "date", "labels", "epilogue")) # Import your downloaded mbox filebox = mbox('All mail Including Spam and Trash.mbox') fails = []for message in box: try: if message.get_content_type() == 'text/plain': df = store_content(message) elif message.is_multipart(): # Grab any plaintext from multipart messages for part in message.get_payload(): if part.get_content_type() == 'text/plain': df = store_content(message, part.get_payload(decode=True)) break except: fails.append(message)
上面使用Python的mailbox模塊讀取并解析mbox格式的郵件。當然還可以使用更加優雅的方法來完成(比如,郵件中包含大量冗余、重復的數據,像回復中嵌入的“>>>”符號)。另外一個問題是無法處理一些特殊的字符,簡單起見,我們進行丟棄處理;確認你在這一步沒有忽略信箱中重要的部分。
新聞熱點
疑難解答