溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python3文本聚類怎樣進(jìn)行分類操作

發(fā)布時(shí)間:2020-11-17 09:19:59 來源:億速云 閱讀:248 作者:小新 欄目:編程語言

這篇文章給大家分享的是有關(guān)Python3文本聚類怎樣進(jìn)行分類操作的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考。一起跟隨小編過來看看吧。

主要有一下幾個(gè)步驟:

切詞

去除停用詞

構(gòu)建詞袋空間VSM(vector space model)

TF-IDF構(gòu)建詞權(quán)重,這部我沒有做,因?yàn)槲业臄?shù)據(jù)基本都是一類的,只是想細(xì)分,所以感覺不太適合,而且這個(gè)也有點(diǎn)難(捂臉)

使用K-means算法

下面開始代碼部分:

 #引入基礎(chǔ)庫,在網(wǎng)上抄的代碼,除了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("\t\t\t","\t"))
 #print(w)
 f1.close()
 f2.close()
 #取需要分詞的內(nèi)容
 titles=open("C:/Users/KangB/Desktop/wechat7/title_fenci.txt",encoding='GB2312',errors='ignore').read().split('\n')
 #查看內(nèi)容,這里是一個(gè)list,list里面每個(gè)原素是分好的標(biāo)題,查看下長度看有沒有錯(cuò)誤
 #titles
 #len(titles)
 #構(gòu)建停詞函數(shù),停詞表是自己在網(wǎng)上搜的
 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
 #停用詞函數(shù)調(diào)用
 stop_words_file="C:/Users/KangB/Desktop/wechat7/stopwords.txt"
 stopwords=get_custom_stopwords(stop_words_file)
 #查看停用詞,也是list格式
 #stopwords
 #構(gòu)建詞向量,也就是把分好的次去除停詞轉(zhuǎn)化成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 #聚為四類,可根據(jù)需要修改
 km = KMeans(n_clusters=num_clusters)
 km.fit(km_matrix)
 clusters = km.labels_.tolist()
 #查看聚類的結(jié)果,是list,這里省略,看看長度是不是和title一樣就行啦
 #len(clusters)
 #最后把聚類結(jié)果寫在一個(gè)新的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()

感謝各位的閱讀!關(guān)于Python3文本聚類怎樣進(jìn)行分類操作就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI