结巴分词&nltk&word2vec用于文本分析

一、结巴分词参考资料:

http://blog.csdn.net/u010454729/article/details/40476483

二、nltk参考资料:

http://www.shareditor.com/blogshow?blogId=64这篇博文包括基本用法,但并没有如何加载自己分词后的文件;

nltk将自定义语料导入成text方法如下:

利用分词工具进行分词,利用nltk.text.Text函数导入。

seglist=jieba.cut(f)
text_ori=nltk.text.Text(seglist)

关于nltk尝试性的小函数(代码参考了其他博主的一篇博文,不贴链接了)

article = read_santi()
word_flags=pseg.cut(article)
word_freq={}
allowedflagn=['n','nr','ns','nt','nz']#定义名词
allowedflagadj=['a','ad','an']#定义形容词
for word_flag in word_flags:
    if (word_flag.flag in allowedflagadj)&(len(word_flag.word)>1):
        if word_flag.word in word_freq:
            word_freq[word_flag.word]+=1
        else:
            word_freq[word_flag.word]=1
freq_word=[]
for word,freq in word_freq.items():
    freq_word.append((word,freq))
freq_word.sort(key=lambda x:x[1],reverse=True)
max_number=int (raw_input("需要前多少位高频词?"))
for word,freq in freq_word[:max_number]:
    print word,freq

三、word2vec:

训练语料使用百度百科,维基百科之种效果会好很多,考虑到训练的时间及机器的配置要求,直接在网上下载了一个模型:http://spaces.ac.cn/archives/4304/comment-page-1

同时博文提到了如何加载模型,及该模型的训练语料和特点。关于word2vec的一些小函数示例:

# -*- coding: utf-8 -*-
import pandas as pd
import gensim
model=gensim.models.Word2Vec.load('word2vec_wx')
res_mostsimilar=pd.Series(model.most_similar(u'开心'))
res_dosentmatch=model.doesnt_match([u'高兴',u'难过',u'伤感',u'开心'])
res_similar=model.similarity(u'日本',u'开心')
res_model=model.wv[u'日本']
res_cosmul=pd.Series(model.wv.most_similar_cosmul(positive=[u'宇宙',u'太阳'], negative=[u'量子']))
print res_mostsimilar

由于下载的语料库关闭了自动识别新词,有些词语可能不在词典中,查找源码成功找到如何判断一个词语是否被词典收录:

model.wv.vocab是词典文件,用if word in model.wv.vocab即可。

(看源码真的很有拓展性,很好玩。)

四、关于文本编码,如果utf8word(utf8型),需要转换成uniword(unicode型),函数:uniword=unicode(utf8word,'utf-8');反过来:utf8word.encode('utf-8')。

具体的可以看:http://blog.sina.com.cn/s/blog_6ce9e8870101gqzt.html

中文处理中常会涉及到编码的转换,一些库对编码的支持很敏感,需要注意。

五、上述函数组合拓展可以实现很强大的功能,等寒假分析自己一年的日记后再补上代码。^.=.^

 

posted @ 2018-01-08 14:45  蔺小渊  阅读(2011)  评论(0编辑  收藏  举报