繁体   English   中英

正则表达式在多个PyMongo文档字段中搜索

[英]Regex Search in Multiple PyMongo Document Fields

目标

搜索Enron电子邮件的语料库,以查找往返于证券欺诈专家Ken Lay的电子邮件。

数据

其中一个这样的电子邮件文档(名为workdocs封电子邮件)的结构如下:

一份这样的文件:

 {'headers': {'To': 'eric.bass@enron.com', 'Subject': 'Re: Plays and other information', 'X-cc': '', 'X-To': 'Eric Bass', 'Date': 'Tue, 14 Nov 2000 08:22:00 -0800 (PST)', 'Message-ID': '<6884142.1075854677416.JavaMail.evans@thyme>', 'From': 'michael.simmons@enron.com', 'X-From': 'Michael Simmons', 'X-bcc': ''}, 'subFolder': 'notes_inbox', 'mailbox': 'bass-e', '_id': ObjectId('4f16fc97d1e2d32371003e27'), 'body': "the scrimmage is still up in the air...\n\n\nwebb said that they didnt want to scrimmage...\n\nthe aggies  are scrimmaging each other... (the aggie teams practiced on \nSunday)\n\nwhen I called the aggie captains to see if we could use their field.... they \nsaid that it was tooo smalll for us to use...\n\n\nsounds like bullshit to me... but what can we do....\n\n\nanyway... we will have to do another practice Wed. night....    and I dont' \nknow where we can practice.... any suggestions...\n\n\nalso,  we still need one  more person..."}

我感兴趣的字段是{'To':...,'From':...,'X-cc':...,'X-bcc':...} ,这些字段位于字段'headers'

实现(和错误)

使用workdocs.find({'$text':{'$search':'klay@enron.com'}})在整个文档中搜索'klay@enron'似乎有效,但是我对捕获带正则表达式的许多可能的电子邮件别名。 如何在ToFromX-bccX-cc字段中找到与正则表达式ken_email匹配的文档(如下)?

from pymongo import MongoClient  
import re
re_email = '^(K|Ken|Kenneth)[A-Z0-9._%+-]*Lay@[A-Z0-9._%+-]+\.[A-Z]{2,4}$'
ken_email = re.compile(re_email, re.IGNORECASE)

要仅搜索这四个字段,可以使用:

(?:to|from|x-b?cc)'\s*:\s*'K[A-Z0-9._%+-]*Lay@[A-Z0-9._%+-]+\.[A-Z]{2,4}

该版本会删除其名字周围的捕获组,这对于进行匹配是不必要的。 (完成正则表达式后提取速度会更快。)

我也不认为有必要验证电子邮件地址。 您已经在寻找除了电子邮件地址之外什么都没有的字段。 您可以进一步缩短正则表达式:

(?:to|from|x-b?cc)'\s*:\s*'K[A-Z0-9._%+-]*Lay

这将具有匹配klay123@example.com的额外奖励


它效率不高(特别是长文本字符串),但是有一些方法可以加快它的速度。 最简单的方法是事先卸下身体。 (这也有助于防止误报。)您只需删除第一个}之后的所有内容。

只是为了踢,这是一个正则表达式来匹配:

\}.*

只需替换为空字符串即可将其删除。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM