您的位置:首页 > 编程语言

对一批文件进行中文分词,分词后输出字符串,示例代码

2019-04-15 21:35 99 查看

简介
学习需要记录一下自己调通的代码,所以简要记录一下。
数据介绍
输入文本为一段话分别为一个文件,eg:neg.0.txt,neg.29.txt。
输出结果示例:酒店,门面,很小,不像,三星级,酒店,入住率,好像,反正,房间,大小,标准,光线,网络,奇差,无比,连不上,服务,
代码

# -*- coding:utf-8 -*-
import codecs
import os
import shutil
import jieba
import jieba.analyse

#Read file and cut
def read_file_cut(file_path, num_recs):
#create path

respath = "C:\\Users\\Administrator\\PycharmProjects\\M_H_Attention\\neg0_99\\result_test"
if os.path.isdir(respath):
shutil.rmtree(respath, True)
os.makedirs(respath)
# jieba.load_userdict('THUOCL_food.txt')#导入用户自定义词典
num = 0
while num< num_recs:
name = "%d" % num
print(name)
fileName = file_path + str(name) + ".txt"
resName = respath + str(name) + ".txt"
source = codecs.open(fileName, 'r',encoding='UTF-8')
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('chinese_stopwords.txt', encoding='UTF-8')] ) # 停用词表
while line!="":
seglist = jieba.cut(line,cut_all=False)  #精确模式
output=''#现定义一个list,(定义一个空字符串用'')
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__':
file_path = "C:\\Users\\Administrator\\PycharmProjects\\M_H_Attention\\neg0_99\\neg."
num_res=100
read_file_cut(file_path,num_res)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐