最近研究需要,所以获取了“豆瓣读书”135本书的简介,分成了135个txt文本文件,利用jieba对其进行中文分词、去除停用词工作,并仍旧保存为135个。
这个代码是在https://yq.aliyun.com/articles/26040这篇文章代码的基础上修改的,把分词、去停用词、字母小写之类的都合在了一起
首先导入需要进行分词的文件以及用户自定义词典,用户自定义词典可以保证分词时,用户自定义的某些词能够被保留下来,例如“东野圭吾”这个作者,没被加入到自定义词典时,会被分成“东野”“圭吾”两个词,这肯定会影响后续研究,将其添加到词典中就不会被拆开了。
- # -*- coding:utf-8 -*-
- import codecs
- import os
- import shutil
- import jieba
- import jieba.analyse
-
-
- #Read file and cut
- def read_file_cut():
- #create path
- path = "E:\\book\\"
- respath = "E:\\fc\\"
- if os.path.isdir(respath):
- shutil.rmtree(respath, True)
- os.makedirs(respath)
- jieba.load_userdict("E:\\dict.txt")#导入用户自定义词典
- num = 1
- while num<=135:
- name = "%d" % num
- fileName = path + str(name) + ".txt"
- resName = respath + str(name) + ".txt"
- source = codecs.open(fileName, 'r')
- if os.path.exists(resName):
- os.remove(resName)
- result = codecs.open(resName, 'w', encoding='utf-8')
- line = source.readline()
- line = line.rstrip('\n')
导入停用词表
- stopwords = {}.fromkeys([ line.strip() for line in codecs.open('C:\\stopwords.txt', encoding='UTF-8') ] #停用词表
分词
- while line!="":
- seglist = jieba.cut(line,cut_all=False) #精确模式
- output=''
- for segs in seglist:
- seg=segs.lower() #英文字母小写
- if seg not in stopwords: #去停用词
- if len(seg)>1: #去掉分词为1个字的结果
- output += seg
- output +=' '
- print (output)
- result.write(output+'\r\n')
- line = source.readline()
- else:
- print ('End file: ' + str(num) )
- source.close()
- result.close()
- num = num + 1
- else:
- print ('End All')
- if __name__ == '__main__':
- read_file_cut()
这是其中一本图书的简介分词后的结果