1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
| import os
from sklearn.utils import shuffle import re import jieba
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn import svm
from sklearn import metrics
import pickle
def read_file(file_path): email_list = [] files = os.listdir(file_path) for file in files: if os.path.isdir(file_path + '/' + file): email_list = email_list + read_file(file_path + '/' + file) else: with open(file_path + '/' + file, 'r', encoding='gbk', errors='ignore') as f: email = f.read()
email = re.sub(r"[^\u4e00-\u9fff]", " ", email) email = re.sub(r"\s{2,}", " ", email) email = email.strip() email = [word for word in jieba.lcut(email) if word.strip() != ' '] email = ' '.join(email)
email_list.append(email)
return email_list
def read_lable(file_path): lable = [] with open(file_path, "r") as f: for l in f.readlines(): if "s" in l: lable.append("spam") else: lable.append("ham")
return lable
def data_process(email, lable): email, lable = shuffle(email, lable, random_state=42)
return email, lable
def data_vectorizer(email,lable): vectoring = TfidfVectorizer(input='content', analyzer='word') x = vectoring.fit_transform(email) y = lable
return x, y, vectoring
def model_train(x_train, y_train): model = svm.LinearSVC() model.fit(x_train, y_train)
return model
def model_test(x_test, y_test): y_pred = model.predict(x_test) print("模型评估报告:\n", metrics.classification_report(y_test, y_pred, digits=2))
def model_save(model, vectorizer): save = input("是否保存训练的模型(y/n):") if save == "y" or "Y": with open('model.pkl', 'wb') as f: pickle.dump(model, f) with open('vectorizer.pkl', 'wb') as f: pickle.dump(vectorizer, f) print("保存成功!") return True else: return False
if __name__ == "__main__": print("-------垃圾邮件检测-------") while True: with open("model.pkl", 'rb') as f: model = pickle.load(f) with open('vectorizer.pkl', 'rb') as f: vectorizer = pickle.load(f) file_path = input("输入需要检测的邮件文件的路径:") with open(file_path, "r", encoding="gbk", errors="ignore") as f: email = f.read() email_list = [email] print(email) x = vectorizer.transform(email_list) y_predict = model.predict(x) print("检测结果为:", y_predict[0])
|