Sử dụng lọc thư rác Bayesian để phân loại email trong Python
Contents
[
Hide
]
Sử dụng Lọc Spam Bayesian
Aspose.Email cung cấp chức năng lọc email bằng bộ phân tích spam Bayesian. Nó cung cấp SpamAnalyzer lớp cho mục đích này. Bài viết này trình bày cách huấn luyện bộ lọc để phân biệt giữa spam và email thông thường dựa trên cơ sở dữ liệu từ.
- Chỉ định đường dẫn thư mục cho các email ham (ham_folder), email spam (spam_folder), email kiểm tra (test_folder), và tệp cơ sở dữ liệu (database_file) cho bộ lọc spam.
- Định nghĩa hàm trợ giúp
print_resultđể in ra thông báo liệu một tin nhắn có được phân loại là spam hay không dựa trên xác suất spam đã tính. - Tạo Spam Analyzer bằng tệp cơ sở dữ liệu, huấn luyện nó với các email từ ham_folder (không phải spam) và spam_folder (spam), rồi lưu cơ sở dữ liệu đã huấn luyện.
- Tải các tệp .eml từ ’test_folder’, phân tích mỗi tệp bằng SpamAnalyzer.test để lấy xác suất spam, và in tiêu đề email cùng phân loại bằng ‘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)