天天看点

自然语言处理---结巴分词结巴分词jieba

结巴分词jieba

  • 结巴分词三种模式

    精确模式: 试图将句子最精确切开

    全模式: 所有可以成词的语句都扫描出来,速度快,不能解决歧义

    搜索引擎模式:在精确模式的基础上对长词再次划分,提高召回率

jieba分词的三种模式的对比1

#jieba分词的三种模式的对比
import jieba

text='在精确模式的基础上对长词再次划分提高召回率'
text_list = jieba.cut(text,cut_all=True)
print('全模式:')
print('/'.join(text_list))

print('精确模式:')
text_list = jieba.cut(text,cut_all =  False)
print('/'.join(text_list))

print('默认模式是精确模式:')
text_list = jieba.cut(text)
print('/'.join(text_list))

print('搜索引擎模式:')
text_list = jieba.cut_for_search(text)
print('/'.join(text_list))           

结果

全模式:

在/精确/模式/的/基础/上/对/长/词/再次/划分/提高/召回/率

精确模式:

在/精确/模式/的/基础/上/对/长词/再次/划分/提高/召回/率

默认模式是精确模式:

在/精确/模式/的/基础/上/对/长词/再次/划分/提高/召回/率

搜索引擎模式:

在/精确/模式/的/基础/上/对/长词/再次/划分/提高/召回/率

高频词提取

主要需要排除干扰项:
   标点符号
   停用词
           
#数据读取
def get_content(path):
    with open(path,'r',encoding='gbk',errors='ignore') as f:
        content=''
        for line in f:
            line=line.strip()#去掉每句话开头和结尾的空格
            content+=line
        return content

def stop_words(path):
    with open(path,'r',encoding='utf-8',errors='ignore') as f:
        return [line.strip() for line in f]

#定义一个高频词函数
def get_TF(words ,topK = 10):
    tf_dic = {}
    for w in words:
        tf_dic[w] = tf_dic.get(w,0)+1#遍历words中的每一个词切片,以词为键,出现的次数为值存储在字典中

    return sorted(tf_dic.items(),key = lambda x:x[1],reverse=True)[:topK]

def main():
    import glob
    import random
    import jieba

    #获取到/data/news/C000013/路径下的所有txt文件的路径
    files  =glob.glob('./data/news/C000013/*.txt')

    #读取所有文件的内容存在corpus的列表中
    corpus = [get_content(x) for x in files]

    #获取一个0到corpus长度的整数随机数
    sample_inx = random.randint(0,len(corpus))

    #使用jieba精确模式分词,
    #split_words = list(jieba.cut(corpus[sample_inx]))
    split_words = [x for x in jieba.cut(corpus[sample_inx]) if x not in stop_words('./data/stop_words.utf8')]
    #打印随机选取的样本
    print('样本之一:'+corpus[sample_inx])
    #打印随机选取的样本的分词情况
    print('样本分词效果:'+'/'.join(split_words))
    #统计显示高频词
    print('样本的topK(10)词:'+str(get_TF(split_words)))
main()           

结果

样本之一:中药注射剂是我国独创的新剂型,具有生物利用度高,作用迅速等特点,能较好地发挥中药治疗急病重症的作用。有人预测,中药注射剂将是我国制药产业未来开拓国际市场独具优势的项目。……….

样本分词效果:中药/注射剂/我国/独创/新/剂型/具有/生物/利用/度高/作用/迅速/特点/发挥/中药/治疗/急病/重症/作用/有人/预测/中药/注射剂/我国/制药/产业/未来/开拓/国际/市场/独具/优势/项目………

样本的topK(10)词:[(‘中药’, 33), (‘注射剂’, 26), (‘不良反应’, 20), (‘中’, 10), (‘发生’, 8), (‘减少’, 7), (‘企业’, 7), (‘药品’, 7), (‘研发’, 6), (‘生产’, 6)]