无需第三方库的Python垃圾邮件检测器:如何同时检测邮件内容与主题
垃圾邮件检测代码优化方案
你的现有代码存在几个局限:函数参数未实际使用、仅检测单固定文件内容、未区分邮件主题与内容、部分关键词(如" !" " .")易导致误判。以下是能实现**批量标记含指定关键词的邮件(覆盖主题与内容)**的优化方案:
def is_spam(email_content, email_subject, spam_keywords): # 统一转为小写,避免大小写匹配遗漏 combined_text = f"{email_subject.lower()} {email_content.lower()}" return any(keyword.lower() in combined_text for keyword in spam_keywords) def scan_emails(directory_path): import os # 整理合理的垃圾邮件关键词列表 spam_keywords = [ "account has been hacked", "urgent", "save on", "big deals", "click this link", "win", "claim your prize", "lucky winner", "click here" ] spam_emails = [] # 遍历目标目录下的所有邮件文件(假设为txt格式,可按需修改) for filename in os.listdir(directory_path): if filename.endswith('.txt'): file_path = os.path.join(directory_path, filename) try: with open(file_path, 'r', errors='ignore') as f: lines = f.readlines() # 假设邮件第一行为主题,后续为内容(可根据实际邮件格式调整) email_subject = lines[0].strip() if lines else "" email_content = ''.join(lines[1:]).strip() if is_spam(email_content, email_subject, spam_keywords): spam_emails.append(filename) except Exception as e: print(f"处理文件 {filename} 时出错: {e}") return spam_emails # 使用示例:扫描当前目录下的所有邮件 spam_list = scan_emails('.') print("检测到的垃圾邮件:") for email in spam_list: print(f"- {email}")
核心改进说明:
- 拆分
is_spam独立函数,专注单封邮件的主题+内容检测,逻辑更清晰 - 支持批量扫描指定目录下的所有邮件,无需逐个手动处理
- 统一转为小写匹配,避免因大小写差异漏判
- 移除易误判的空格标点类关键词,提升检测准确性
- 增加异常处理,避免单个文件读取失败导致程序中断
适配调整提示:
- 若邮件为非txt格式(如eml),需修改文件后缀判断及内容拆分逻辑
- 可根据需求扩展关键词列表,或添加关键词出现次数阈值等进阶规则
内容的提问来源于stack exchange,提问作者Cameron Darries
相关产品推荐
相关产品推荐

