ベイズスパムフィルタリングを使用して Python でメールを分類する
Contents
[
Hide
]
ベイズスパムフィルタリングの使用
Aspose.Email はベイズスパムアナライザを使用したメールフィルタリング機能を提供します。以下を提供します SpamAnalyzer この目的のためのクラスです。本記事では、単語データベースに基づいてスパムと通常メールを区別できるようフィルタを訓練する方法を示します。
- スパムフィルタ用に、ハムメール(ham_folder)、スパムメール(spam_folder)、テストメール(test_folder)のフォルダパスとデータベースファイル(database_file)を指定します。
- ヘルパー関数を定義する
print_result計算されたスパム確率に基づいて、メッセージがスパムかどうかを出力します。 - Spam Analyzer を作成し、ham_folder(スパムでないメール)と spam_folder(スパムメール)のメールで ’train_filter(message, is_spam)’ メソッドを使って学習させ、学習済みデータベースを ‘save_database(file_path)’ で保存します。
- Spam Analyzer を作成し、’load_database(file_path)’ で学習済みデータベースを復元し、’test_folder’ から .eml ファイルをロードし、各ファイルを ’test(message)’ で分析してスパム確率を取得し、‘print_result’ でメールの件名と分類結果を表示します。
import os
from aspose.email import MailMessage
from aspose.email.antispam import SpamAnalyzer
ham_folder = "hamFolder"
spam_folder = "spamFolder"
test_folder = "testFolder"
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 train_from_directory(analyzer, folder, is_spam):
for file in os.listdir(folder):
if file.endswith(".eml"):
analyzer.train_filter(MailMessage.load(os.path.join(folder, file)), is_spam)
def teach_and_create_database(ham_folder, spam_folder, database_file):
analyzer = SpamAnalyzer()
train_from_directory(analyzer, ham_folder, False)
train_from_directory(analyzer, spam_folder, True)
analyzer.save_database(database_file)
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()
analyzer.load_database(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)