python 去除停用词 结巴分词

本文通过一个简单的例子展示了如何使用jieba进行中文文本的分词处理,并去除停用词。代码中定义了一个包含部分停用词的小型停用词表,然后对‘北京附近的租房’这一短句进行了分词,并过滤掉停用词。
#coding:gbk
import jieba
#stopwords = {}.fromkeys([ line.rstrip() for line in open('stopword.txt') ])
stopwords = {}.fromkeys(['的', '附近'])
segs = jieba.cut('北京附近的租房', cut_all=False)
final = ''
for seg in segs:
    seg = seg.encode('gbk')
    if seg not in stopwords:
            final += seg
print final
### Python 中使用 Jieba 分词处理停用词 在自然语言处理任务中,去除停用词是一项重要的预处理工作。对于中文文本而言,Jieba 是一种广泛使用的分词工具。 #### 加载停用词列表 为了实现停用词过滤,在程序初始化阶段需先读取停用词文件中的词条到内存中形成集合或列表结构以便后续快速查询匹配[^1]: ```python def stopwordslist(filepath): with open(filepath, 'r', encoding='utf-8') as f: stopwords = [line.strip() for line in f.readlines()] return set(stopwords) ``` #### 文本分词停用词过滤 完成上述准备工作之后就可以编写具体逻辑来执行实际的分词停用词移除操作了。下面这段代码展示了如何结合 `jieba.cut()` 函数来进行基本的分词,并通过判断是否属于之前准备好的停用词表来决定保留哪些词汇[^4]: ```python import jieba def seg_sentence(sentence, stopwords): outstr = '' sentence_seged = jieba.cut(sentence.strip()) for word in sentence_seged: if word not in stopwords and word != '': outstr += word + " " return outstr.strip() ``` 此部分实现了对输入字符串`sentence`按照空格分割成多个单词组成的单个字符串形式返回;其中忽略了所有出现在给定参数`stopwords`(即前面定义的那个包含停用词项的数据集)里的项目以及空白字符。 #### 完整示例流程 最后给出一个完整的例子说明整个过程是如何运作的: ```python if __name__ == "__main__": input_file_path = './input.txt' output_file_path = './output.txt' stop_words_path = './test/stopwords.txt' # 初始化停用词列表 stopwords = stopwordslist(stop_words_path) outputs = [] with open(input_file_path, 'r', encoding='utf-8') as fin: lines = fin.readlines() for line in lines: result = seg_sentence(line, stopwords) outputs.append(result) with open(output_file_path, 'w', encoding='utf-8') as fout: for item in outputs: fout.write(item + '\n') ``` 该脚本会依次读入指定路径下的每行文字内容作为待处理对象,经过分词噪后保存至另一文件内供进一步分析之用。
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值