python中文文本分类

前言

在做文本挖掘的时候,很多时候都需要分词,中文分词不跟英文分词一样,词语与词语之间没有天然的空隙,这时候就需要我们专门去解决这个问题了。

除去非中文部分

虽然使用的是中文文档,但是不免有一些非中文的部分,这时候就需要将那些非中文的部分去掉,运用下面代码可以将文本中的标点符号清除,被清除的字符用空格代替:

def is_ustr(in_str):
    out_str=''
    for i in range(len(in_str)):
        if is_uchar(in_str[i]):
            out_str=out_str+in_str[i]
        else:
            out_str=out_str+' '
    return out_str
def is_uchar(uchar):
    """判断一个unicode是否是汉字"""
    if uchar >= u'\u4e00' and uchar<=u'\u9fa5':
        return True
    else:
        return False
        

中文分词

推荐使用结巴分词,只需要pip install jieba就可以了,运用下面的代码,可以将刚刚使用去除非中文字符之后的字符串进行分词

def jieba_main(out_str):
    cut_str = jieba.cut(out_str)
    cut_str = ' '.join(cut_str)
    return cut_str

读取文档并且去除非中文部分,在利用jieba分词处理

将需要分类的文档保存到一个文件夹下面,移动到我们的py文件目录中。
以下代码创建一个空数组,之后会读取文件并且去除非中文部分,在利用jieba分词处理。
在文本在处理之后,用‘.append’方法将我们的已经处理之后的文本添加到我们的空数组wei[ ]之中

def main():
    path = './aaa'#需要进行文本分类的文本的文件夹路径
    wei = []#空数组
    listdir = os.listdir(path)#列出文件夹下的文件名
    length = len(listdir)#长度
    for i in listdir:
        begin_path = path + '/' + i
        #读取文件并且除去非文本部分,分词
        with open(begin_path) as f:
            word = f.read()
            word = is_ustr(word)
            words = jieba_main(word)
            wei.append(words)
    return wei

引用停用词

这样的分词有一个缺陷,就是没有引用停用词,在一个文本之中,有的词对我们的非类是没有一点帮助的,比如的,是,等等一切这样的词语,所以我们可以引用停用词,将这些词去掉,这样我觉得文本分类的结果更加具有说服力,下载地址在这,当然还有一些其他版本的停用词,不过这些是我们常用的,可以根据个人实际情况增减。

在我们用scikit-learn做特征处理的时候,可以通过参数stop_words来引入一个数组作为停用词表。

现在我们将停用词表从文件读出,并切分成一个数组备用:

#从文件导入停用词表
def yy_stpword():
    stpwrdpath = "./stop_words.txt"#停用词文本路径
    with open(stpwrdpath, 'rb') as f:
        stpwrd_content = f.read()
    #将停用词表转换为list  
        stpwrdlst = stpwrd_content.splitlines()
        print(stpwrdlst)
    return stpwrdlst

进行向量化,TF-IDF和标准化

想了解文本向量化,TF-IDF和标准化请戳这里
在这里我们传入上面经过处理之后的文本数组wei[ ],停用词在这里也得到了使用
将包含文本文档且经过简单处理之后的wei[ ]数组进行向量化,TF-IDF处理和标准化

#传入我们上面return的wei数组
def tf(wei):
    vector = TfidfVectorizer(stop_words=yy_stpword())#引用停用词
    tfidf = vector.fit_transform(wei)#
    d = tfidf.toarray()
    return d

K-means 算法聚类

K-means算法介绍请戳这里
我们传入上面经过 tf()函数向量化,TF-IDF和标准化的特征向量 “d ”。
这会将特征向量d[ ]里面的特征值分类。

def km(d):
    k = 4 #将所有文本分成4类,可自定义设置
    clf = KM(k)
    kmns = clf.fit_predict(d)
    return kmns

优化main()函数

现在我们优化我们的main()函数,并且将文本分类之后的结果使之更加清楚。
使用fenlei(numb,ga)函数,处理我们分类的结果,将同一类的文本文档保存到同一个文件夹下。

def main():
    path = './aaa'#需要进行文本分类的文本的文件夹路径
    wei = []#空数组
    listdir = os.listdir(path)#列出文件夹下的文件名
    length = len(listdir)#长度
    for i in listdir:
        begin_path = path + '/' + i
        #读取文件并且除去非文本部分,分词
        with open(begin_path) as f:
            word = f.read()
            word = is_ustr(word)
            words = jieba_main(word)
            wei.append(words)
    tfs = tf(wei)  #将文本向量化,TF-IDF和标准化
    kms = km(tfs)    #K--means聚类算法聚类  
    for i in range(length):
        pdb.set_trace()
        fenlei(listdir[i],kms[i])
def fenlei(numb,ga):
    path = '.'
    begin_path = path + '/' + numb
    paths = '../' + str(ga) 
    folder = os.path.exists(paths)
    if folder:
        path_d = paths + '/' + str(numb) 
        shutil.move(begin_path,path_d)
    else:
        os.makedirs(paths)
        path_d = paths + '/' + str(numb) 
        shutil.move(begin_path,path_d)

总体test.py代码

亲测有效

import os
import shutil
import jieba
import pdb


def main():
    path = './aaa'#需要进行文本分类的文本的文件夹路径
    wei = []#空数组
    listdir = os.listdir(path)#列出文件夹下的文件名
    length = len(listdir)#长度
    for i in listdir:
        begin_path = path + '/' + i
        #读取文件并且除去非文本部分,分词
        with open(begin_path) as f:
            word = f.read()
            word = is_ustr(word)
            words = jieba_main(word)
            wei.append(words)
    tfs = tf(wei)  #将文本向量化,TF-IDF和标准化
    kms = km(tfs)    #K--means聚类算法聚类  
    for i in range(length):
        fenlei(listdir[i],kms[i])


#除去非中文部分
def is_ustr(in_str):
    out_str=''
    for i in range(len(in_str)):
        if is_uchar(in_str[i]):
            out_str=out_str+in_str[i]
        else:
            out_str=out_str+' '
    return out_str
def is_uchar(uchar):
    """判断一个unicode是否是汉字"""
    if uchar >= u'\u4e00' and uchar<=u'\u9fa5':
        return True
    else:
        return False

#jieba中文分词
def jieba_main(out_str):
    cut_str = jieba.cut(out_str)
    cut_str = ' '.join(cut_str)
    return cut_str


### 进行向量化,TF-IDF处理和标准化一步到位
from sklearn.feature_extraction.text import TfidfVectorizer
#传入我们上面return的wei数组
def tf(wei):
    vector = TfidfVectorizer(stop_words=yy_stpword())#引用停用词
    tfidf = vector.fit_transform(wei)#
    d = tfidf.toarray()
    return d
#引用停用词
def yy_stpword():
    stpwrdpath = "./stop_words.txt"#停用词文本路径
    with open(stpwrdpath, 'rb') as f:
        stpwrd_content = f.read()
    #将停用词表转换为list  
        stpwrdlst = stpwrd_content.splitlines()
    return stpwrdlst


#K-means 算法聚类
from sklearn.cluster import KMeans as KM
def km(d):
    k = 4 #将所有文本分成4类
    clf = KM(k)
    kmns = clf.fit_predict(d)
    return kmns

#处理分类结果
def fenlei(numb,ga):
    path = '.'
    begin_path = path + '/aaa/' + numb
    paths = './' + str(ga) 
    folder = os.path.exists(paths)
    if folder:
        path_d = paths + '/' + str(numb) 
        shutil.move(begin_path,path_d)
    else:
        os.makedirs(paths)
        path_d = paths + '/' + str(numb) 
        shutil.move(begin_path,path_d)


if __name__ == '__main__':
    main()

文件目录结构

——stop_words.txt
——test.py
——aaa #文件夹

stop_word.txt:下载的停用词文本
test.py:python代码
aaa:存放我们需要分类的文本文档

  • 2
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值