词云:jieba分词
2018-10-26 本文已影响39人
冷小谦
jieba是中文分词工具,安装很简单直接pip install jieba
github:https://github.com/fxsjy/jieba
三种分词模式
jieba中有三种分词模式,分别是:全模式,默认模式和搜索引擎模式
import jieba
seg_list = jieba.cut("我在北京大学吃着炸鸡",cut_all=True,HMM=False)
print("Full Mode:"+"/".join(seg_list))#全模式
seg_list = jieba.cut("我在北京大学吃着炸鸡",cut_all=False,HMM=True)
print("Default Mode:"+'/'.join(seg_list))#默认模式
seg_list = jieba.cut("我在北京大学吃着炸鸡",HMM=False)
print(','.join(seg_list))
seg_list = jieba.cut_for_search("小明硕士毕业于中国科学院计算所,后在日本京都大学深造", HMM=False) # 搜索引擎模式
print(", ".join(seg_list))
image.png
jieba.cut的默认参数只有三个,jieba源码如下:
cut(self, sentence, cut_all=False, HMM=True)
分别为:输入文本 是否为全模式分词 与是否开启HMM进行中文分词。
一般来说用默认模式就可以(cut_all=False)
关键词提取
步骤很简单
1.找到文本路径path
2.获取文本open(path)read()
3.使用analyse.extract_tags方法提取
jieba.analyse.extract_tags(sentence, topK=20, withWeight=False, allowPOS=())
sentence 为待提取的文本
topK 为返回几个 TF/IDF 权重最大的关键词,默认值为 20
withWeight 为是否一并返回关键词权重值,默认值为 False
allowPOS 仅包括指定词性的词,默认值为空,即不筛选
from os import path
import jieba.analyse as analyse
import codecs
d_path = path.dirname(__file__)#返回脚本路径
ab_path = path.abspath(__file__)#返回脚本绝对路径
text_path = 'pml1.txt'#设置要分析的文本的路径
text = open(path.join(d_path,text_path)).read()
file = open('./demo.txt', 'wb+')
for keyWord in analyse.extract_tags(text,50,withWeight=True):
#得到的是tuple不是str,列表和元组转换为字符串则必须依靠str()或者__str__()
#print(keyWord)
file.write(str(keyWord).encode('utf-8'))
file.write('\n'.encode('utf-8'))
file.close()
这里注意分词后得到的是tuple,写入到txt文件需要转换类型。
分析缥缈录第一卷,得到以下的结果:
会发现有"像是","可是"这种非名词,这种词可以使用去除停用词的方法,将其解决。
去除停用词
需要下载一个停用词词表,可以直接从这里复制https://github.com/ziqian9206/stopword。
有了停用词表,就可以用来剔除停用词。
from os import path
import jieba.analyse as analyse
import jieba
d_path = path.dirname(__file__)#返回脚本路径
ab_path = path.abspath(__file__)#返回脚本绝对路径
stopword_path = './stopwords1893.txt'
text_path = 'pml1.txt'#设置要分析的文本的路径
text = open(path.join(d_path,text_path)).read()
file = open('./demo.txt', 'wb+')
#封装函数可以剔除停用字
def jiebaclean(text):
wordlist = []
seg_list = jieba.cut(text,cut_all=False)
liststr = "/ ".join(seg_list)
#读取停用词,去除回车,去除文本的分隔符/,判断去除空格的被遍历词在停用词中,且被遍历词长度大于1.
f_stop = open(stopword_path)
f_stop_text = f_stop.read()
f_stop_text = str(f_stop_text)
f_stop.close()
f_stop_seg_list = f_stop_text.split('\n')
for word in liststr.split('/'):
if not(word.strip() in f_stop_seg_list) and len(word.strip())>1:
wordlist.append(word)
return str(wordlist)
cleartext = jiebaclean(text)
for keyWord in analyse.extract_tags(cleartext,50,withWeight=True):
#得到的是tuple不是str,列表和元组转换为字符串则必须依靠str()或者__str__()
file.write(keyWord.encode('utf-8'))
file.write('\n'.encode('utf-8'))
file.close()
使用停用词之后,很多无用词被剔除。
此外我们还可以在jieba中添加自定义词语。
jieba.add_word(text)
频次
使用count可以得到频次值
from collections import Counter
count_words = [word for word in jieba.cut(text,cut_all=False) if len(word) > 1]
#for word in xxxx:
# if(word):
c = Counter(count_words)
for word in c.most_common(50):
word,freq = word
print(word,freq)
使用jieba分词后我们得到了词云的文本。