python jieba分词如何去除停用词

Python013

python jieba分词如何去除停用词,第1张

-*- coding: utf-8 -*-

import jieba

import jieba.analyse

import sys

import codecs

reload(sys)

sys.setdefaultencoding('utf-8')

#使用其他编码读取停用词表

#stoplist = codecs.open('../../file/stopword.txt','r',encoding='utf8').readlines()

#stoplist = set(w.strip() for w in stoplist)

#停用词文件是utf8编码

stoplist = {}.fromkeys([ line.strip() for line in open("../../file/stopword.txt") ])

#经过分词得到的应该是unicode编码,先将其转成utf8编码

在用 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()

我觉得是这样啦:

...

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

seglist = (seg.encode('utf-8') for seg in seglist)

seglist = [seg for seg in seglist if seg not in stopwords]

output = ' '.join(seglist)

print output

...

不太懂你这两行的意思:

output+=seg

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

每次 output 都会被设定成 ' '.join(list(seglist)) 那 output+=seg 好像就没有意义了。

python中最好不要在list遍历中使用list.remove方法:

remove 仅仅 删除一个值的首次出现。 

如果在 list 中没有找到值,程序会抛出一个异常

最后,你遍历自己时候对自己的内容进行删除操作,效率显然不高,还容易出现各种难debug的问题

建议使用新的list存储要保留的内容,然后返回这个新list。比如

a_list = [1,2,3,4,5]

needs_to_be_removed = [3,4,5]

result = []

for v in a_list:

    if v not in needs_to_be_removed:

        result.append(v)

print result