python gensim的第一次試用


參考於

http://blog.csdn.net/xiaoquantouer/article/details/53583980

 

有一個地方很重要,一定要安裝anaconda,安裝庫簡直不要太方便。

先進行python jieba庫進行中文分詞:

 1 #encoding=utf-8
 2 import jieba
 3 import jieba.posseg as pseg
 4 import re
 5 import sys
 6 reload(sys)
 7 sys.setdefaultencoding( "utf-8" )
 8 filename='D:/hellowxc/python/1.txt'
 9 fileneedCut='D:/hellowxc/python/test.txt'
10 fn=open(fileneedCut,"r")
11 f=open(filename,"w+")
12 lines =fn.readlines()  # 讀取全部內容
13 for line in lines:
14     line.replace('\t', '').replace('\n', '').replace(' ','')
15     seg_list = jieba.cut(line, cut_all=False)
16     f.write(" ".join(seg_list))
17 f.close()
18 fn.close()

然后gensim和word2vec進行簡單的訓練建模

 1 # -*- coding: utf-8 -*-
 2 
 3 """
 4 功能:測試gensim使用,處理中文語料
 5 時間:2017年5月16日17:10:23
 6 """
 7 
 8 from gensim.models import word2vec
 9 import logging
10 # 主程序
11 logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
12 sentences = word2vec.Text8Corpus(u"D:\\hellowxc\\python\\1.txt")  # 加載語料
13 model = word2vec.Word2Vec(sentences, size=200)
14 #
15 print model
16 # 計算兩個詞的相似度/相關程度
17 try:
18     y1 = model.similarity(u"屋頂", u"建成")
19 except KeyError:
20     y1 = 0
21 print u"【屋頂】和【建成】的相似度為:", y1
22 print"-----\n"
23 
24 y2 = model.most_similar(u"屋頂", topn=20)  # 20個最相關的
25 print u"和【屋頂】最相關的詞有:\n"
26 for item in y2:
27     print item[0], item[1]
28 print"-----\n"
29 
30 # 尋找對應關系
31 print u"屋頂-建成,形狀-"
32 y3 =model.most_similar([u'建成', u'形狀'], [u'屋頂'], topn=3)
33 for item in y3:
34     print item[0], item[1]
35 print"----\n"
36 
37 # 尋找不合群的詞
38 y4 =model.doesnt_match(u"屋頂 建成 形狀 酒店".split())
39 print u"不合群的詞:", y4
40 print"-----\n"

由於我數據特別小,只有6k,純粹就是試用一下gensim。result沒有任何意義。就不貼出來了。

just for test,走一遍大概的流程。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM