天天看点

Python使用jieba分词处理语料

前言:在中文分词中,结巴分词可以算是十分优秀的分词工具之一了,所以这次我就用jieba分词来处理语料,以便为我的词向量做增量更新

结巴分词的GitHub地址

准备

可以使用 Pip install jieba 来安装结巴分词库

先贴几个结巴分词常用的方法:

# encoding=utf-8
import jieba

seg_list = jieba.cut("我来到北京清华大学", cut_all=True)
print("Full Mode: " + "/ ".join(seg_list))  # 全模式

seg_list = jieba.cut("我来到北京清华大学", cut_all=False)
print("Default Mode: " + "/ ".join(seg_list))  # 精确模式

seg_list = jieba.cut("他来到了网易杭研大厦")  # 默认是精确模式
print(", ".join(seg_list))

seg_list = jieba.cut_for_search("小明硕士毕业于中国科学院计算所,后在日本京都大学深造")  # 搜索引擎模式
print(", ".join(seg_list))
           

输出:

【全模式】: 我/ 来到/ 北京/ 清华/ 清华大学/ 华大/ 大学

【精确模式】: 我/ 来到/ 北京/ 清华大学

【新词识别】:他, 来到, 了, 网易, 杭研, 大厦    (此处,“杭研”并没有在词典中,但是也被Viterbi算法识别出来了)

【搜索引擎模式】: 小明, 硕士, 毕业, 于, 中国, 科学, 学院, 科学院, 中国科学院, 计算, 计算所, 后, 在, 日本, 京都, 大学, 日本京都大学, 深造
           

其他的方法可自行参考结巴GitHub上的例子,很简单,很容易学会。

正文

我使用的是结巴的精确模式,为了去掉语料中的数字我加了一个判断数字的方法。

其中corpus.txt文件是需要分词的语料,curpus_t.txt是分完词的语料,需要先自己创建一个文件

停用词可以去GitHub上下一个,在这里我就不提供了

import jieba

#判断是否为数字
def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        pass
    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError):
        pass

    return False
# 创建停用词list
def stopwordslist(filepath):
    stopwords = [line.strip() for line in open(filepath, 'r', encoding='utf-8').readlines()]
    return stopwords

# 对句子进行分词
def cut_sentence(sentence):
    sentence = jieba.cut(sentence,cut_all=False)    # 精确模式
    stopwords = stopwordslist('stop_word.txt')  # 这里加载停用词的路径
    outstr = ''
    # 去除停用词,逐个加词
    for w in sentence:
        if (w not in stopwords) and ('.' not in w) and (' ' not in w) and (not is_number(w)):
            outstr += w
            outstr += ' '
    print(outstr)
    return outstr

# 执行主方法
if __name__ == '__main__':
    f = open("corpus.txt",encoding='UTF-8')
    line = f.readline()
    f2 = open("curpus_t.txt",'w',encoding='UTF-8')
    while line:
        cut_s = cut_sentence(line)
        f2.write(cut_s)
        line = f.readline()
    f.close()
    print("分词完毕")
           

下面这个是未分词的语料:

Python使用jieba分词处理语料

下面是分词的语料结果:

Python使用jieba分词处理语料

整体效果还是不错的