
本教程旨在解决从outlook邮件正文中,根据配置的父子关键词,精确提取关联文本和url的挑战。通过分析原有正则表达式的局限性,引入并详细解析了新的、更强大的正则表达式模式,该模式能一次性捕获关键词、其所在段落及紧随的url,并提供了完整的python实现代码,帮助开发者优化邮件内容自动化处理流程。
在日常工作中,我们经常需要从大量的邮件中筛选出特定信息,例如根据关键词识别邮件主题,并从邮件正文中提取与这些关键词相关的具体内容和链接。Python结合win32com.client库可以方便地与Microsoft Outlook进行交互,而正则表达式则是从非结构化文本中提取结构化数据的强大工具。然而,构建一个能够精确捕获所需信息(如关键词、其上下文文本以及紧随其后的URL)的正则表达式,往往是实现这一目标的关键挑战。
原始的Python代码尝试通过以下步骤提取信息:
然而,这种方法的局限性在于:
例如,对于以下邮件内容:
立即学习“Python免费学习笔记(深入)”;
01 事務用品・機器 大阪府警察大正警察署:指サック等の購入 :大阪市大正区 https://www.e-nyusatsu.pref.osaka.jp/CALS/Publish/EbController?Shori=SmallKokokuInfo&open_kokoku=01202350042214
如果子关键词是“事務用品・機器”,原代码中的paragraph_text可能只包含“01 事務用品・機器”,而无法包含后续的描述文本和URL。
为了解决上述问题,我们需要一个更强大的正则表达式,能够一次性捕获关键词、其关联文本以及紧随其后的URL。核心思想是利用正则表达式的捕获组和非贪婪匹配,跨越多行来定位所有相关信息。
我们构建的优化正则表达式如下:
rf'([^
]*({"|".join(map(re.escape, child_keywords))})[^
]*).*?(https?://S+)'让我们分解这个正则表达式的各个部分:
([^ ]*):
({"|".join(map(re.escape, child_keywords))}):
[^ ]*: 匹配关键词之后在同一行的零个或多个非换行符。
.*?:
(https?://S+):
关键的正则表达式标志:
我们将更新 search_and_save_email 函数中的子关键词匹配和信息提取部分。
import win32com.client
import os
import json
import logging
import re
def read_config(config_file):
with open(config_file, 'r', encoding="utf-8") as f:
config = json.load(f)
return config
def search_and_save_email(config):
try:
folder_name = config.get("folder_name", "")
output_file_path = config.get("output_file_path", "")
output_file_name = config.get("output_file_name", "output.txt") # Use a default name or generate per email
parent_keyword = config.get("parent_keyword", "")
child_keywords = config.get("child_keywords", [])
# 确保输出目录存在
os.makedirs(output_file_path, exist_ok=True)
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
user_folder = None
for folder in inbox.Folders:
if folder.Name == folder_name:
user_folder = folder
break
if user_folder is not None:
# 编译父关键词正则表达式,用于主题匹配
parent_keyword_pattern = re.compile(r'(?:' + '|'.join(map(re.escape, parent_keyword.split())) + r')', re.IGNORECASE)
# 编译子关键词、关联文本和URL的正则表达式
# 注意 re.S (DOTALL) 标志,使 '.' 匹配换行符
# 注意 re.IGNORECASE 标志,使匹配不区分大小写
child_url_extraction_pattern = re.compile(
rf'([^
]*({"|".join(map(re.escape, child_keywords))})[^
]*).*?(https?://S+)',
re.S | re.IGNORECASE
)
for item in user_folder.Items:
# 检查邮件主题是否包含父关键词
if parent_keyword_pattern.findall(item.Subject):
logging.info(f"在主题中找到父关键词: {item.Subject}")
email_body = item.Body # 使用原始邮件正文
output_content = ""
# 使用新的正则表达式在邮件正文中查找所有匹配项
# re.findall 返回一个列表,其中每个元素是一个元组,包含所有捕获组的内容
matches = child_url_extraction_pattern.findall(email_body)
if matches:
for full_line_text, child_matched_keyword, url in matches:
# full_line_text 包含了关键词所在行及其前后文本
# child_matched_keyword 是实际匹配到的子关键词
# url 是紧随其后的URL
output_content += f"子关键词: {child_matched_keyword.strip()}
"
output_content += f"关联文本: {full_line_text.strip()}
"
output_content += f"URL: {url}
"
# 根据邮件主题生成文件名,并保存结果
# 替换主题中的非法文件名字符
safe_subject = re.sub(r'[\/:*?"<>|]', '_', item.Subject)
output_file = os.path.join(output_file_path, f"{safe_subject}.txt")
with open(output_file, 'w', encoding='utf-8') as f:
f.write(output_content)
logging.info(f"结果已保存到 {output_file}")
else:
logging.warning(f"在邮件主题 '{item.Subject}' 中找到父关键词,但未找到匹配的子关键词或URL。")
# else:
# # 如果父关键词未找到,这里可以跳过或记录
# logging.debug(f"未在主题中找到父关键词: {item.Subject}")
else:
logging.warning(f"文件夹 '{folder_name}' 未找到。")
except Exception as e:
logging.error(f"发生错误: {str(e)}")
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
config_file_path = "E:\config2.json" # 请根据实际路径修改
# 示例配置文件内容 (config2.json)
# {
# "folder_name": "调达プロジェクト",
# "output_file_path": "E:\output",
# "output_file_name": "output.txt",
# "parent_keyword": "meeting",
# "child_keywords": ["土木一式工事", "産業用機器", "事務用品・機器"]
# }
if not os.path.exists(config_file_path):
logging.error(f"配置文件 '{config_file_path}' 不存在。请检查路径或创建文件。")
else:
config = read_config(config_file_path)
search_and_save_email(config)
通过优化正则表达式,我们成功解决了从Outlook邮件正文中精确提取关键词、关联文本和URL的难题。新的正则表达式模式结合 re.S 和 re.IGNORECASE 标志,能够一次性、跨行地捕获所有所需信息,大大提高了数据提取的准确性和效率。这一方法不仅适用于邮件处理,也为其他复杂的文本内容提取任务提供了宝贵的参考。理解正则表达式的各个组成部分及其标志的用途,是掌握高效文本处理能力的关键。
以上就是Python正则表达式从邮件正文高效提取关键词、文本及URL教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号