# 导库
# 用于分词
import jieba
# 用于数据分析
import pandas as pd
# 合并为csv数据进行数据操作
import csv
# 用于计算运行时间
import time
import joblib
# 创建停用词列表
def stopwordslist():
stopwords = [line.strip() for line in open('./HGD_StopWords.txt',encoding='UTF-8').readlines()]
return stopwords
# 对句子进行中文分词
def seg_depart(sentence):
# 对文档中的每一行进行中文分词
#print("正在分词")
sentence_depart = jieba.cut(sentence.strip())
# 引进停用词列表
stopwords = stopwordslist()
# 输出结果为outstr
outstr = ''
# 去停用词
for word in sentence_depart:
if word not in stopwords:
if word != '\t':
outstr += word
outstr += " "
return outstr
# 给出文档路径
filename = "./data.txt"
outfilename = "./stop_seg_word.txt"
inputs = open(filename, 'r', encoding='UTF-8')
outputs=open(outfilename, 'w', encoding='UTF-8')
# 将输出结果写入out中
count=0
for line in inputs:
line_seg = seg_depart(line)
#writer.writerows(line_seg + '\n')
outputs.writelines(line_seg + '\n')
#print("-------------------正在分词和去停用词-----------")
count=count+1
print("一共处理了",count,"条数据")
outputs.close()
inputs.close()
print("删除停用词和分词成功!!!")
# 查看分词后的数据
with open("./stop_seg_word.txt") as f:
lines=f.readlines()
for line in lines:
print(line)
#创建方法对象
data = pd.DataFrame()
#将txt文件中的数据按行写入csv文件
with open('./stop_seg_word.txt', encoding='utf-8') as f:
line = f.readlines()
line = [i.strip() for i in line]
print(len(line))
#建立短信这一列,将数据进行循环写入
data['短信'] = line
# 查看标签
all_labels=[]
with open('./label.txt', "r",encoding='utf-8') as f:
all_label=f.readlines()
all_labels.extend([x.strip() for x in all_label if x.strip() != '']) # 不为空
print(all_label)
print(type(all_label))
print(len(all_label))
all_labels
#建立“是否涉堵”这一列,将数据进行循环写入
data['是否涉赌'] = all_labels
#将整理好的数据进行保存,文件保存为同目录下chat_score_update.csv
data.to_csv('./chat_score_update.csv')
机器学习
# 导包
import pandas as pd
import numpy as np
import jieba
import re
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn import model_selection
from sklearn import preprocessing
#将数据进行读取
data=pd.read_csv('./chat_score_update.csv',index_col=0)
data.head()
#现在是划分数据集
#random_state 取值,这是为了在不同环境中,保证随机数取值一致,以便验证模型的实际效果。
train_x,test_x,train_y,test_y=model_selection.train_test_split(data.短信.values.astype('U'),data.是否涉赌.values,test_size=0.1,random_state=1)
#划分完毕,查看数据形状
print(train_x.shape,test_x.shape)
#train_x 训练集数据 test_x 测试集数据 train_y训练集的标签 test_y 测试集的标签
#定义函数,从哈工大中文停用词表里面,把停用词作为列表格式保存并返回 在这里加上停用词表是因为TfidfVectorizer和CountVectorizer的函数中
#可以根据提供用词里列表进行去停用词
def get_stopwords(stop_word_file):
with open(stop_word_file) as f:
stopwords=f.read()
stopwords_list=stopwords.split('\n')
custom_stopwords_list=[i for i in stopwords_list]
return custom_stopwords_list
#获得由停用词组成的列表
stop_words_file = './HGD_StopWords.txt'
stopwords = get_stopwords(stop_words_file)
'''
使用TfidfVectorizer()和 CountVectorizer()分别对数据进行特征的提取,投放到不同的模型中进行实验
'''
#开始使用TF-IDF进行特征的提取,对分词后的中文语句做向量化。
#引进TF-IDF的包
TF_Vec=TfidfVectorizer(max_df=0.8,min_df = 3,stop_words=frozenset(stopwords))
#拟合数据,将数据准转为标准形式,一般使用在训练集中
train_x_tfvec=TF_Vec.fit_transform(train_x)
#通过中心化和缩放实现标准化,一般使用在测试集中
test_x_tfvec=TF_Vec.transform(test_x)
#开始使用CountVectorizer()进行特征的提取。它依据词语出现频率转化向量。并且加入了去除停用词
CT_Vec=CountVectorizer(max_df=0.8,#在超过这一比例的文档中出现的关键词(过于平凡),去除掉。
min_df = 3,#在低于这一数量的文档中出现的关键词(过于独特),去除掉。
token_pattern=u'(?u)\\b[^\\d\\W]\\w+\\b',#使用正则表达式,去除想去除的内容
stop_words=frozenset(stopwords))#加入停用词)
#拟合数据,将数据转化为标准形式,一般使用在训练集中
train_x_ctvec=CT_Vec.fit_transform(train_x)
#通过中心化和缩放实现标准化,一般使用在测试集中
test_x_ctvec=CT_Vec.transform(test_x)
### Random Forest Classifier 随机森林分类器
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
import time
start_time=time.time()
#创建模型
Rfc = RandomForestClassifier(n_estimators=8)
#拟合从CounterfVectorizer拿到的数据
Rfc.fit(train_x_ctvec,train_y)
#在训练时查看训练集的准确率
pre_train_y=Rfc.predict(train_x_ctvec)
#在训练集上的正确率
train_accracy=accuracy_score(pre_train_y,train_y)
#训练结束查看预测 输入测试集查看预测
pre_test_y=Rfc.predict(test_x_ctvec)
#查看在测试集上的准确率
test_accracy = accuracy_score(pre_test_y,test_y)
print('使用CounterfVectorizer提取特征使用随机森林分类器的准确率\n训练集:{0}\n测试集:{1}'.format(train_accracy,test_accracy))
end_time=time.time()
print("使用随机森林分类器的程序运行时间为",end_time-start_time)
joblib.dump(Rfc, './RandomForest.pkl') # 保存模型
load_model = joblib.load('./RandomForest.pkl')
result=pd.DataFrame({'proba':load_model.predict_proba(test_x_ctvec)[:,1]})
result.head()
SHuang=result.loc[result.proba>0.5].count()
Data_total=result.count()
rate=SHuang/Data_total
print('测试集中共有%d条数据,根据模型预测,其中%d条数据具有涉赌性质,占比约%.4f%%' % (Data_total,SHuang,rate))
print('所有涉赌博数据为:',result.loc[result.proba>0.5])
print('第9条涉赌数据为:',test_x[9])
result.loc[result.proba>0.5].to_csv('./finnal.csv')
#输出所有的涉黄内容
fin = list()
with open('./finnal.csv', "r") as f:
reader = csv.reader(f)
for row in reader:
fin.append(row[0])
for i in range(1,10):
a = fin[i]
print('第'+a+'条赌博内容:'+test_x[int(a)])