python提取停用词_如何用python对一个文件夹下的多个txt文本进行去停用词。

本文探讨了在Python中使用jieba库进行文本处理时,遇到部分停用词未被正确移除且重复去除的问题。通过阅读代码并分析,发现问题可能出在过滤停用词时的条件判断上。解决方法可能需要确保对每个seg进行完整检查并避免重复处理。
摘要由CSDN通过智能技术生成

在用 for 循环去停用词的部分,出错,仅去掉了 stopwords 中的部分停用词,且相同停用词只去除了一次。求大神告知错误之处,贴上代码再好不过!!

#encoding=utf-8

import sys

import re

import codecs

import os

import shutil

import jieba

import jieba.analyse

#导入自定义词典

#jieba.load_userdict("dict_baidu.txt")

#Read file and cut

def read_file_cut():

#create path

stopwords = {}.fromkeys([ line.strip() for line in open('stopword.txt') ])

path = "Lon\\"

respath = "Lon_Result\\"

if os.path.isdir(respath): #如果respath这个路径存在

shutil.rmtree(respath, True) #则递归移除这个路径

os.makedirs(respath) #重新建立一个respath目录

num = 1

while num<=20:

name = "%d" % num

fileName = path + str(name) + ".txt"

resName = respath + str(name) + ".txt"

source = open(fileName, 'r')

if os.path.exists(resName):

os.remove(resName)

result = codecs.open(resName, 'w', 'utf-8')

line = source.readline()

line = line.rstrip('\n')

while line!="":

line = unicode(line, "utf-8")

output=''

seglist = jieba.cut(line,cut_all=False)

for seg in seglist:

seg=seg.encode('utf-8')

if seg not in stopwords:

output+=seg

output = ' '.join(list(seglist))#空格拼接

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'

#Run function

if __name__ == '__main__':

read_file_cut()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值