这段代码功能为将中文文本进行分词并去除停用词,使用了 jieba 和 gensim 两个库。具体含义如下:

  1. 定义 'stopwordslist' 函数,读取停用词文件并返回停用词列表。

  2. 定义 'seg_depart' 函数,将一个句子进行中文分词并去除停用词,返回分词后的字符串。

  3. 如果文档还未进行分词,就进行分词。具体步骤如下:

    (1) 给出文档路径,读取未分词的文本文件。 (2) 把每行文本中非汉字的字符全部去掉,提取出文本内容。 (3) 调用 'seg_depart' 函数进行分词和去停用词操作。 (4) 将分词后的结果写入一个新的文本文件中。

  4. 最后输出成功信息。

代码示例:

#!/usr/bin/python
# -*- coding:utf-8 -*-
import jieba,os,re
from gensim import corpora, models, similarities

'创建停用词列表'
def stopwordslist():
    stopwords = [line.strip() for line in open('./stopwords.txt',encoding='UTF-8').readlines()]
    return stopwords

'对句子进行中文分词'
def seg_depart(sentence):
    sentence_depart = jieba.cut(sentence.strip())
    stopwords = stopwordslist()
    outstr = ''
    for word in sentence_depart:
        if word not in stopwords:
            outstr += word
            outstr += ' '
    # outstr:'黄蜂 湖人 首发 科比 带伤 战 保罗 加索尔 ...'
    return outstr

'如果文档还没分词,就进行分词'
if not os.path.exists('./cnews.train_jieba.txt'):
    # 给出文档路径
    filename = './cnews.train.txt'
    outfilename = './cnews.train_jieba.txt'
    inputs = open(filename, 'r', encoding='UTF-8')
    outputs = open(outfilename, 'w', encoding='UTF-8')
    
    # 把非汉字的字符全部去掉
    # 将输出结果写入ouputs.txt中
    for line in inputs:
        line = line.split('	')[1]
        line = re.sub(r'[^一-龥]+','',line)
        line_seg = seg_depart(line.strip())
        outputs.write(line_seg.strip() + '
')
        
    outputs.close()
    inputs.close()
    print('删除停用词和分词成功!!!')
Python 中文文本分词与去停用词代码详解

原文地址: https://www.cveoy.top/t/topic/mQef 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录