• Python 自然语言处理 文本分类 地铁方面留言文本


    将关于地铁的留言文本进行自动分类。

    不要着急,一步步来。

    导入需要的库。

    1. import numpy as np
    2. import pandas as pd
    3. import jieba # 分词
    4. import re # 正则
    5. from fnmatch import fnmatch # 通配符
    6. from sklearn.preprocessing import LabelEncoder
    7. from sklearn.feature_extraction.text import CountVectorizer # 文本向量化
    8. from sklearn.feature_extraction.text import TfidfTransformer # 文本向量化
    9. from sklearn.model_selection import train_test_split
    10. from sklearn.metrics import classification_report, confusion_matrix
    11. from sklearn import svm # 支持向量机模型

    定义函数,加载用来分词的自定义词典。

    1. # 可根据实际需要,手动调整自定义词典路径和自定义词汇
    2. def jieba_fenci():
    3. # 在jieba中加载自定义的地铁线路名、地铁站点名词典
    4. jieba.load_userdict("mydict_line.csv")
    5. jieba.load_userdict("mydict_station.csv")
    6. # 一些在市民留言中常见的高频的词,发现了就手动添加进去
    7. myaddword_ls = ["公共自行车", "金溪园"]
    8. for w in myaddword_ls:
    9. jieba.add_word(w)

    定义函数,生成自己的停用词词典,得到一个文件。

    我找的4个停用词词典下载地址:https://gitcode.net/mirrors/goto456/stopwords/-/tree/master

    后面我会把自己整合好的停用词词典上传。

    1. # 这段代码只用跑一次,以后可以直接用这个文件
    2. # 自己给停用词文件起好名字(路径),作为投入函数的参数
    3. def get_mystopwords_file(mystopwords_file_name):
    4. stopwords_path_ls = ["baidu_stopwords.txt", "cn_stopwords.txt", "hit_stopwords.txt", "scu_stopwords.txt"]
    5. stopwords_set = set() # 集合可以自动去重
    6. for p in stopwords_path_ls:
    7. with open(p, 'r', encoding = 'utf-8') as stopwords_file:
    8. for stopword in stopwords_file:
    9. if u'\u4e00'<= stopword[0] <= u'\u9fff': # 只放中文的停用词
    10. stopwords_set.add(stopword.strip('\n'))
    11. with open(mystopwords_file_name, 'w') as mystopwords_file:
    12. for stopword in stopwords_set:
    13. mystopwords_file.write(stopword + '\n')

    定义函数,读取停用词词典文件,得到一个停用词列表。

    1. # 可以根据实际需要,手动添加或删除停用词
    2. def get_mystopwords_list(mystopwords_file_name):
    3. mystopwords_ls = []
    4. with open(mystopwords_file_name, 'r') as mystopwords_file:
    5. for stopword in mystopwords_file:
    6. mystopwords_ls.append(stopword.strip('\n'))
    7. # 对于一些高频出现的、但对于分类没什么特征帮助的词,可以手动加进停用词列表
    8. zdy_stopword = ["建议", "信访", "杭州"]
    9. for w in zdy_stopword:
    10. mystopwords_ls.append(w)
    11. # 对于一些停用词表里有的、但认为对后面分析有用的词,可以手动从停用词列表剔除
    12. zdy_not_stopword = [] # 目前还没想好剔除什么词,所以列表是空的
    13. for w in zdy_not_stopword:
    14. mystopwords_ls.remove(w)
    15. return mystopwords_ls

    定义函数,统一地铁线路名称格式。

    1. # 投入参数是一个已经分好词的列表,返回一个处理好的列表
    2. def unify_line_name(mylist):
    3. num_dict = {1:'一', 2:'二', 3:'三', 4:'四', 5:'五', 6:'六', 7:'七', 8:'八', 9:'九', \
    4. 10:'十', 11:'十一', 12:'十二', 13:'十三', 14:'十四', 15:'十五', 16:'十六', 17:'十七', \
    5. 18:'十八', 19:'十九', 20:'二十', 21:'二十一', 22:'二十二', 23:'二十三'}
    6. for i in range(len(mylist)):
    7. if fnmatch(mylist[i], "*号线") or fnmatch(mylist[i], "*号地铁"):
    8. for j in range(len(num_dict),0,-1):
    9. if str(j) in mylist[i] or num_dict[j] in mylist[i]:
    10. mylist[i] = "地铁" + str(j) + "号线"
    11. break
    12. if mylist[i] in ["机场快线", "机场轨道快线"]:
    13. mylist[i] = "地铁19号线"
    14. return mylist

    定义文本预处理的函数,作用:去除无用字符、去除停用词、统一地铁线路名。

    1. # 投入的参数是一个原始字符串,返回一个处理好的字符串(分好的词之间空格连接)
    2. # 要在使用这个函数之前弄好停用词列表,列表名称是mystopwords_ls
    3. def mychuli(x):
    4. # 仅保留汉字、英文字母、阿拉伯数字
    5. mystr = ''.join(re.findall('[a-zA-Z0-9\u4e00-\u9fa5]',x))
    6. # 分词,每个字符串变成一个列表
    7. mylist = jieba.lcut(mystr, cut_all = False)
    8. # 统一线路名称
    9. mylist = unify_line_name(mylist)
    10. # 去除停用词
    11. for word in mylist:
    12. if word in mystopwords_ls:
    13. mylist.remove(word)
    14. return ' '.join(mylist)

    定义模型实际应用的函数,输入文本,输出分类结果。

    1. # 输入一条文本,经预处理后投进支持向量机模型进行预测
    2. def mypre():
    3. lebel_dict = dict(zip([0,1,2,3,4,5,6,7,8,9], le.inverse_transform([0,1,2,3,4,5,6,7,8,9])))
    4. mytext = input("输入要预测的文本:")
    5. mytext_yichuli = mychuli(mytext)
    6. print("文本预处理结果:{}".format(mytext_yichuli))
    7. X_new = []
    8. X_new.append(mytext_yichuli)
    9. X_new_vec = tf.fit_transform(cv_new.fit_transform(X_new)).toarray()
    10. y_new_pre = SVM.predict(X_new_vec)
    11. print("模型预测的分类编号为:{}".format(y_new_pre[0]))
    12. print("对应的分类名称为:{}".format(lebel_dict[y_new_pre[0]]))

    读取文本,去重。

    1. # 读取语料文件
    2. df = pd.read_csv("xxx.csv")
    3. print("去重前:")
    4. print(df.info())
    5. # 去除重复数据
    6. df1 = df.drop_duplicates()
    7. print("去重后:")
    8. print(df1.info())
    9. print(df1.head())

    1. jieba_fenci() # 加载自定义的分词词典
    2. get_mystopwords_file("mystopwords.txt") # 得到一个整合好的停用词文件,只用跑一次
    3. mystopwords_ls = get_mystopwords_list("mystopwords.txt") # 得到停用词列表
    4. # 新建一列yichuli_title,放已经处理好的文本数据
    5. df1['yichuli_title'] = df1['title'].apply(mychuli)
    6. # 给类别进行编号
    7. le = LabelEncoder()
    8. le.fit(df1['class1'])
    9. df1['yichuli_label'] = le.transform(df1['class1'])
    10. # 把处理好的结果写入一个新的csv文件,方便以后使用
    11. # 用gb18030编码可实现外面打开这个文件看显示正常中文,而不是乱码
    12. df1.to_csv("test0908_result.csv", columns = ['yichuli_title', 'yichuli_label', 'class1'], encoding = "gb18030")

    构建训练集、测试集。 

    1. # 读取已经处理好的csv文件
    2. df1 = pd.read_csv("test0908_result.csv", encoding = "gb18030")
    3. # 构建训练集、测试集
    4. cv = CountVectorizer()
    5. tf = TfidfTransformer()
    6. X = df1['yichuli_title']
    7. y = df1['yichuli_label']
    8. X = tf.fit_transform(cv.fit_transform(X)).toarray()
    9. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=1)
    10. print(X_train.shape)
    11. print(X_test.shape)

    训练模型。

    1. SVM = svm.LinearSVC() #支持向量机分类器LinearSVC
    2. SVM.fit(X_train, y_train)
    3. y_pre = SVM.predict(X_test)
    4. print("支持向量机模型结果:")
    5. print(classification_report(y_test, y_pre))
    6. # 支持向量机的混淆矩阵
    7. svm_confuse = pd.DataFrame(confusion_matrix(y_test, y_pre))
    8. print(svm_confuse)

    预测新数据。

    1. cv_new = CountVectorizer(vocabulary = cv.vocabulary_) # vocabulary参数保证向量维度与训练集一致
    2. mypre()

  • 相关阅读:
    Gateway服务网关
    求平均查找长度(成功+失败)
    网址导航收藏引导页面H5源码(自适应引导页HTML源码)-自动检测域名延迟
    快来玩AI画图!StableDiffusion模型搭建与使用入门~
    JAVA设计模式-单例模式
    ETL数据转换方式有哪些
    【Spring Boot】响应JSON实现原理
    Cell子刊:器官再生,这种病可以让受损的肝脏再生
    深度学习——(7)分类任务
    【阿良的算法之路】图论最短路算法模板
  • 原文地址:https://blog.csdn.net/lxx199603/article/details/132763386