【发布时间】:2016-02-02 16:38:17
【问题描述】:
我在 Windows 上运行 Python 2.7。
我有一个包含 500K+ 电子邮件的大文本文件 (2 GB)。该文件没有明确的文件类型,格式为:
email_message#: 1
email_message_sent: 10/10/1991 02:31:01
From: tomf@abc.com| Tom Foo |abc company|
To: adee@abc.com| Alex Dee |abc company|
To: benfor12@xyz.com| Ben For |xyz company|
email_message#: 2
email_message_sent: 10/12/1991 01:28:12
From: timt@abc.com| Tim Tee |abc company|
To: tomf@abc.com| Tom Foo |abc company|
To: adee@abc.com| Alex Dee |abc company|
To: benfor12@xyz.com| Ben For|xyz company|
email_message#: 3
email_message_sent: 10/13/1991 12:01:16
From: benfor12@xyz.com| Ben For |xyz company|
To: tomfoo@abc.com| Tom Foo |abc company|
To: t212@123.com| Tatiana Xocarsky |numbers firm |
...
如您所见,每封电子邮件都有以下相关数据:
1) 发送时间
2) 发送邮件的电子邮件地址
3) 发送者的姓名
4) 该人工作的公司
5) 收到电子邮件的每个电子邮件地址
6) 收到电子邮件的每个人的姓名
7) 收到电子邮件的每个人的公司
在文本文件中有超过 50 万封电子邮件,并且电子邮件最多可以有 16,000 个收件人。电子邮件中提到的人名或他们工作的公司的方式没有规律。
我想获取这个大文件并在python 中对其进行操作,使其最终成为Pandas Dataframe。我想要pandas dataframe 的格式类似于下面excel 的屏幕截图:
编辑
我解决这个问题的计划是编写一个“解析器”,它接收这个文本文件并读取每一行,将每一行中的文本分配给 pandas dataframe 的特定列。
我打算写一些类似下面的东西。有人可以确认这是执行此操作的正确方法吗?我想确保我没有遗漏内置的pandas 函数或来自不同module 的函数。
#connect to object
data = open('.../Emails', 'r')
#build empty dataframe
import pandas as pd
df = pd.DataFrame()
#function to read lines of the object and put pieces of text into the
# correct column of the dataframe
for line in data:
n = data.readline()
if n.startswith("email_message#:"):
#put a slice of the text into a dataframe
elif n.startswith("email_message_sent:"):
#put a slice of the text into a dataframe
elif n.startswith("From:"):
#put slices of the text into a dataframe
elif n.startswith("To:"):
#put slices of the text into a dataframe
【问题讨论】:
-
@whoever 否决了这个问题。你能简要解释一下你为什么投反对票吗?在这个问题上,即使是正确的方向,我也会很感激
-
对不起@BeeGee,我在做的时候分心了。这将有助于了解您的努力以及您实际在哪里挣扎。否则,唯一可能的答案是为您编写解析器,我认为这不是重点。您只是在编写一些要求并要求提供代码。除此之外,这个问题很清楚并且写得很好,我愿意提供帮助。
-
@Goyo 感谢您帮助我解决我的问题。我将编写自己的解析器,如果确实没有模块,我会发布我的解决方案
-
不,如果您正在为该工作寻找一个单一的衬垫,我认为至少在 python 标准库或熊猫中没有。
标签: python python-2.7 pandas dataframe datasource