最新公告
  • 欢迎您光临知事网软件APP资源下载站,一个优质的手机App应用商店和网站源码基地。欢迎加入永久SVIP
  • Python3文本聚类如何进行分类操作?

    正文概述 知事网   2020-11-16 09:11:04   420

    不知道小伙伴们有没有这种情况,想要给表格中的某一列内容分个类,有没有什么特别好的解决办法呢?小编觉得python中的文本聚类文本聚类不错,分类的速度比较快,而且不会以出现分类混乱的问题。小编整理了有关文本聚类用来分类的代码,分享给小伙伴们一起尝试一下。

    主要有一下几个步骤:

    切词

    去除停用词

    构建词袋空间VSM(vector space model)

    TF-IDF构建词权重,这部我没有做,因为我的数据基本都是一类的,只是想细分,所以感觉不太适合,而且这个也有点难(捂脸)

    使用K-means算法

    下面开始代码部分:

     #引入基础库,在网上抄的代码,除了1、2、6,其他的可能用不到
     import numpy as np
     import pandas as pd
     import re
     import os
     import codecs
     import jieba
     #打开文件,文件在桌面上,可以自行修改路径
     f1=open("C:/Users/KangB/Desktop/wechat7/title.txt","r",encoding='GB2312',errors='ignore')
     f2=open("C:/Users/KangB/Desktop/wechat7/title_fenci.txt",'w',encoding='GB2312',errors='ignore')
     for line in f1:
     seg_list = jieba.cut(line, cut_all=False)
     f2.write((" ".join(seg_list)).replace("ttt","t"))
     #print(w)
     f1.close()
     f2.close()
     #取需要分词的内容
     titles=open("C:/Users/KangB/Desktop/wechat7/title_fenci.txt",encoding='GB2312',errors='ignore').read().split('n')
     #查看内容,这里是一个list,list里面每个原素是分好的标题,查看下长度看有没有错误
     #titles
     #len(titles)
     #构建停词函数,停词表是自己在网上搜的
     def get_custom_stopwords(stop_words_file):
     with open(stop_words_file,encoding='utf-8')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="C:/Users/KangB/Desktop/wechat7/stopwords.txt"
     stopwords=get_custom_stopwords(stop_words_file)
     #查看停用词,也是list格式
     #stopwords
     #构建词向量,也就是把分好的次去除停词转化成kmeans可以接受的形式
     from sklearn.feature_extraction.text import CountVectorizer
     count_vec=CountVectorizer(stop_words=stopwords)
     km_matrix= count_vec.fit_transform(titles)
     print(km_matrix.shape)
     #查看词向量
     #print(km_matrix.toarray())
     #开始聚类啦
     from sklearn.cluster import KMeans
     num_clusters = 4 #聚为四类,可根据需要修改
     km = KMeans(n_clusters=num_clusters)
     km.fit(km_matrix)
     clusters = km.labels_.tolist()
     #查看聚类的结果,是list,这里省略,看看长度是不是和title一样就行啦
     #len(clusters)
     #最后把聚类结果写在一个新的txt里面
     f3 =open("C:/Users/KangB/Desktop/wechat7/title_clusters.txt", 'w',encoding='GB2312',errors='ignore')
     for i in clusters:
     f3.write(str(i))
     f3.write("n")
     f3.close()

    最后把原始数据title和聚类结果title_clusters在一个excel里面不同列打开就可以啦。

    不知道有没有小伙伴们试了文本聚类的分类方法,是不是跟小编说的一样好用呢?小编相信试过的小伙伴,肯定下次还会使用这种分类方法的。

    转载自:python学习网 https://www.py.cn/


    知事网 » Python3文本聚类如何进行分类操作?

    发表评论

    还没有评论,快来抢沙发吧!

    [!--temp.right--]
    请选择支付方式
    ×
    余额支付
    ×
    微信扫码支付 0 元