赞
踩
(1)、jieba库概述
jieba是优秀的中文分词第三方库
- 中文文本需要通过分词获得单个的词语
- jieba是优秀的中文分词第三方库,需要额外安装
- jieba库提供三种分词模式,最简单只需掌握一个函数
(2)、jieba分词的原理
Jieba分词依靠中文词库
- 利用一个中文词库,确定汉字之间的关联概率
- 汉字间概率大的组成词组,形成分词结果
- 除了分词,用户还可以添加自定义的词组
(1)、jieba分词的三种模式
精确模式、全模式、搜索引擎模式
- 精确模式:把文本精确的切分开,不存在冗余单词
- 全模式:把文本中所有可能的词语都扫描出来,有冗余
- 搜索引擎模式:在精确模式基础上,对长词再次切分
(2)、jieba库常用函数
- #-*- coding:utf-8-*-
- __author__="huitao"
- import jieba
- str="python怎么安装jieba库这个模块,很多ytho初学者有时候需要用到jiea库,但是不清楚怎么安装,下面来分享下安装jiea库的方法"
- def jieci():
- listos=jieba.lcut(str)
- print(listos)
- for p in listos:
- print(p)
- #通过文件读取分词,进行统计词语出现的次数
- def duTxt():
- txt = open("../htt.txt", "r", encoding='utf-8').read()
- words = jieba.lcut(txt) # 使用精确模式对文本进行分词
- counts = {} # 通过键值对的形式存储词语及其出现的次数
-
- for word in words:
- if len(word) == 1: # 单个词语不计算在内
- continue
- else:
- counts[word] = counts.get(word, 0) + 1 # 遍历所有词语,每出现一次其对应的值加 1
-
- items = list(counts.items()) # 将键值对转换成列表
- items.sort(key=lambda x: x[1], reverse=True) # 根据词语出现的次数进行从大到小排序
-
- for i in range(15):
- word, count = items[i]
- print("{0:<5}{1:>5}".format(word, count))
-
- #停用词提取
- def tyc():
- stripword=[line.strip() for line in open("../hui.txt",ecoding="utf-8").readline()]
- return stripword
-
- # 对句子进行中文分词
- def seg_depart(sentence):
- # 对文档中的每一行进行中文分词
- print("正在分词")
- sentence_depart = jieba.cut(sentence.strip())
- # 创建一个停用词列表
- stopwords = tyc()
- # 输出结果为outstr
- outstr = ''
- # 去停用词
- for word in sentence_depart:
- if word not in stopwords:
- if word != '\t':
- outstr += word
- outstr += " "
- return outstr
-
-
- if __name__=="__main__":
- jieci()
- duTxt()
-
- #文件路径
- filename="In.txt";
- outfilename="out.txt";
- inputs=open(filename,'rb')
- outputs=open(outfilename,'r')
-
- # 将输出结果写入ou.txt中
- for line in inputs:
- line_seg=seg_depart(line)
- outputs.write(line_seg+'\n')
-
- inputs.close()
- outputs.close()
- #inputs里面就存储了去除停用词的文本
- #outputs里面就存储了需要保留的文本内容

亲测可以使用!!!!!!!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。