ベイズスパムフィルタリングを使用して Python でメールを分類する

ベイズスパムフィルタリングの使用

Aspose.Email はベイズスパムアナライザを使用したメールフィルタリング機能を提供します。以下を提供します SpamAnalyzer この目的のためのクラスです。本記事では、単語データベースに基づいてスパムと通常メールを区別できるようフィルタを訓練する方法を示します。

  1. スパムフィルタ用に、ハムメール(ham_folder)、スパムメール(spam_folder)、テストメール(test_folder)のフォルダパスとデータベースファイル(database_file)を指定します。
  2. ヘルパー関数を定義する print_result 計算されたスパム確率に基づいて、メッセージがスパムかどうかを出力します。
  3. データベースファイルを使用してスパムアナライザを作成し、ham_folder(スパムではない)と spam_folder(スパム)のメールで訓練し、訓練済みデータベースを保存します。
  4. 「test_folder」から .eml ファイルをロードし、各ファイルを SpamAnalyzer.test で分析してスパム確率を取得し、‘print_result’ を使用してメールの件名と分類を出力します。
from aspose.email import MailMessage, SaveOptions, MsgLoadOptions, MessageFormat, FileCompatibilityMode
from aspose.email.antispam import SpamAnalyzer
import os

ham_folder = "/hamFolder"
spam_folder = "/Spam"
test_folder = data_dir
database_file = "SpamFilterDatabase.txt"

def print_result(probability):
    if probability >= 0.5:
        print("The message is classified as spam.")
    else:
        print("The message is classified as not spam.")
    print("Spam Probability: " + str(probability))
    print()

def teach_and_create_database(ham_folder, spam_folder, database_file):
    analyzer = SpamAnalyzer(database_file)
    analyzer.teach_from_directory(ham_folder, True)
    analyzer.teach_from_directory(spam_folder, False)
    analyzer.save_database()

teach_and_create_database(ham_folder, spam_folder, database_file)

test_files = [f for f in os.listdir(test_folder) if f.endswith(".eml")]
analyzer = SpamAnalyzer(database_file)

for file in test_files:
    file_path = os.path.join(test_folder, file)
    msg = MailMessage.load(file_path)
    print(msg.subject)
    probability = analyzer.test(msg)
    print_result(probability)