中文分词

#分词
#读分词词典,词典中最长词长度
def get_word_dict(dictpath):
    max_index = 1
    with open('dict.txt','r',encoding='utf-8') as f:
        dictwords =f.readlines()
    word_dict = set()
    for word in dictwords:
        word_dict.add(word.strip())
        if len(word)>max_index:
            max_index = len(word)
    return word_dict,max_index
#读取停用词词典
def get_stop_words(stopwordpath):
    with open('dict.txt','r',encoding='utf-8') as f:
        stopwords =f.readlines()
    stop_words = set()
    for word in stopwords:
        stop_words.add(word.strip())
    return stop_words

#分词,返回list
def cut(sentence,dictpath,stopwordpath='dict/stopwords.txt',del_stopword=False):
    start_index = 1
    end_index = len(sentence)

    word_dict, max_index = get_word_dict(dictpath)

    result_sentence = []
    while start_index > 0:
        for start_index in range(max(end_index - max_index, 0), end_index, 1):
            if del_stopword:
                stop_words = get_stop_words(stopwordpath)
                if sentence[start_index:end_index] in stop_words:
                    break
            if sentence[start_index:end_index] in word_dict or end_index == start_index + 1:
                str = sentence[start_index:end_index]
                result_sentence.append(str)
                break
        end_index = start_index

    return result_sentence

结巴分词使用:

http://blog.csdn.net/alis_xt/article/details/53522435

http://blog.csdn.net/wangpei1949/article/details/57077007

转载于:https://my.oschina.net/u/3673704/blog/1570124

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值