首页 > 解决方案 > 清理用于文本分析 python 的电子邮件链

问题描述

我有一些文字:

text = """From: 'Mark Twain' <mark.twain@gmail.com>
To: 'Edgar Allen Poe' <eap@gmail.com>
Subject: RE:Hello!

Ed,

I just read the Tell Tale Heart. You\'ve got problems man.

Sincerely,
Marky Mark

From: 'Edgar Allen Poe' <eap@gmail.com>
To: 'Mark Twain' <mark.twain@gmail.com>
Subject: RE: Hello!

Mark,

The world is crushing my soul, and so are you.

Regards,
Edgar"""

看起来像这样:

"From: 'Mark Twain' <mark.twain@gmail.com>\nTo: 'Edgar Allen Poe' <eap@gmail.com>\nSubject: RE:Hello!\n\nEd,\n\nI just read the Tell Tale Heart. You've got problems man.\n\nSincerely,\nMarky Mark\n\nFrom: 'Edgar Allen Poe' <eap@gmail.com>\nTo: 'Mark Twain' <mark.twain@gmail.com>\nSubject: RE: Hello!\n\nMark,\n\nThe world is crushing my soul, and so are you.\n\nRegards,\nEdgar"

我正在尝试解析其中的消息。最终,我希望有一个列表或字典,其中包含 From 和 To,然后是用于进行一些分析的消息正文。

我尝试通过将所有内容调低,然后进行字符串拆分来解析它。

text = text.lower()
text = text.translate(string.punctuation)
text_list = text.split('+')
text_list = [x for x in text_list if len(x) != 0]

有一个更好的方法吗?

标签: pythontext

解决方案


这不是如何str.translate工作的。您text.translate(string.punctuation)使用标点符号作为翻译表,因此它将代码点 10 的“\n”映射到 中的第 10 个字符string.punctuation,即“+”。通常的使用方法str.translate是首先使用创建转换表str.maketrans,它允许您指定要映射的字符、要映射到的相应字符以及(可选)要删除的字符。如果您只想将其用于删除,您可以使用创建表dict.fromkeys,例如

table = dict.fromkeys([ord(c) for c in string.punctuation])

这使得 dict 将每个 char 的代码点关联string.punctuationNone.

这是您的代码的修复版本,用于str.translate在一个步骤中执行大小写转换和标点符号删除。

# Map upper case to lower case & remove punctuation
table = str.maketrans(string.ascii_uppercase, 
    string.ascii_lowercase, string.punctuation)

text = text.translate(table)
text_list = text.split('\n')
for row in text_list:
    print(repr(row))

输出

'from mark twain marktwaingmailcom'
'to edgar allen poe eapgmailcom'
'subject rehello'
''
'ed'
''
'i just read the tell tale heart youve got problems man'
''
'sincerely'
'marky mark'
''
'from edgar allen poe eapgmailcom'
'to mark twain marktwaingmailcom'
'subject re hello'
''
'mark'
''
'the world is crushing my soul and so are you'
''
'regards'
'edgar'

但是,简单地删除所有标点符号有点麻烦,因为它会加入一些您可能不想加入的单词。相反,我们可以将每个标点字符转换为空格,然后在空格上拆分:

# Map all punctuation to space
table = dict.fromkeys([ord(c) for c in string.punctuation], ' ')
text = text.translate(table).lower()
text_list = text.split()
print(text_list)

输出

['from', 'mark', 'twain', 'mark', 'twain', 'gmail', 'com', 'to', 'edgar', 'allen', 'poe', 'eap', 'gmail', 'com', 'subject', 're', 'hello', 'ed', 'i', 'just', 'read', 'the', 'tell', 'tale', 'heart', 'you', 've', 'got', 'problems', 'man', 'sincerely', 'marky', 'mark', 'from', 'edgar', 'allen', 'poe', 'eap', 'gmail', 'com', 'to', 'mark', 'twain', 'mark', 'twain', 'gmail', 'com', 'subject', 're', 'hello', 'mark', 'the', 'world', 'is', 'crushing', 'my', 'soul', 'and', 'so', 'are', 'you', 'regards', 'edgar']

推荐阅读