import jiebafrom jieba import analyseimport numpyimport gensimimport codecsimport pandas as pdimport jieba.posseg as pogfrom gensim.models import Word2Vecfrom gensim.models.word2vec import LineSentence#获取训练语料def data_handle(data):    n = data.shape[0]    data_str = ''    for i in numpy.arange(n):        data_str += str(data.ix[i, 'comment'])    return data_strdef fenci(data_str,stop_property,stopfile):    # 停用词    stop_word = [word.strip() for word in open(stopfile, encoding='utf-8').readlines()]    # 分词    word_cut = pog.cut(data_str)

    with open('weibo.txt','w',encoding='utf-8') as f:        for word, flag in word_cut:            if flag not in stop_property:                if word not in stop_word:                    f.write(word+'\n')

# 原始的训练语料转化成一个sentence的迭代器,每一次迭代返回的sentence是一个word(utf8格式)的列表def vctor_word():    wiki_news = open('weibo.txt', 'r',encoding='utf-8')    sentences=LineSentence(wiki_news)    model=Word2Vec(sentences,sg=0,size=100,window=5,min_count=5,workers=9)    model.save('weibo.word2vec')

# 实现给出任意字符串,获取字符串中某字符的位置以及出现的总次数def get_char_pos(string, char):    chPos = []    try:        chPos = list(((pos, char) for pos, val in enumerate(string) if (val == char)))    except:        pass    return chPos

# 利用训练好的词向量获取关键词的词向量

def cut_data(data,stopfile):    data.fillna(0,inplace=True)    stop_word = [word.strip() for word in open(stopfile, encoding='utf-8').readlines()]    charater=['a', 'nr', 'ns', 'nt', 'ng', 'vn', 'vi', 'l', 'n', 'v']    m=data.shape[0]    with open('seg_word.txt', 'w', encoding='utf-8') as f:

       for i in range(m):            str_cut = ''            str=data.ix[i,'comment']            if str!=0:                segs=jieba.posseg.cut(str)                for word,flag in segs:                    if flag in charater:                        if word not in stop_word:                             str_cut+=word+'/'                f.write(str_cut )            else:               str_cut=''            f.write('\n ')

def get_vector(data,model):#str    wordvec_size = 100    word_vec_all = numpy.zeros(wordvec_size)    space_pos = get_char_pos(data, '/')    first_word = data[0:space_pos[0][0]]    print('first_word', first_word)    if first_word in model:        print('yes')        word_vec_all = word_vec_all + model[first_word]

    for i in range(len(space_pos) - 2):        word = data[space_pos[i][0]:space_pos[i + 1][0]]        print('word',word)        if word in model:            print('yes')            word_vec_all = word_vec_all + model[first_word]

    print('word_vec_all',word_vec_all)    return word_vec_all

def word2vec(file_name, model,str):

   DataFile = codecs.open(file_name, "r", encoding='utf-8')   DataSet = DataFile.readlines()[:-1]

   score_list=[]

   str_vector=get_vector(str,model)   for data in DataSet:  #       if data.strip()!='':           word_vec_all=get_vector(data,model)           score=simlarityCalu(word_vec_all, str_vector)       else:           score=0       score_list.append(score)   print('score_list',score_list)   return score_list

# 词向量相似度计算代码:余弦def simlarityCalu(vector1, vector2):    vector1Mod = numpy.sqrt(vector1.dot(vector1))    vector2Mod = numpy.sqrt(vector2.dot(vector2))    if vector2Mod != 0 and vector1Mod != 0:        simlarity = (vector1.dot(vector2)) / (vector1Mod * vector2Mod)    else:        simlarity = 0    return simlarity

if __name__ == '__main__':

    stop_property = ['b', 'c', 'd', 'e', 'f', 'm', 'o', 'p', 'q', 'r', 't', 'u', 'x', 'y', 'z', 'uj', 'nrt', 'eng',                     'zg', 'ul']    stop_file='stop.txt'

    # 读取数据    data = pd.read_excel('C:/E/weibo.xlsx')    data.rename(columns={'粉丝ID': 'fans_id', '粉丝': 'fans_name', '微博账户id': 'weibo_user_id', '微博名': 'weibo_name',                         '微博id': 'weibo_id', '评论id': 'comment_id', '评论': 'comment'}, inplace=True)

    # 获取评论字符串    comment_str=data_handle(data)

    #获取语料    fenci(comment_str, stop_property, stop_file)    #训练模型    vctor_word()    #获取关键词    cut_data(data, stop_file)

    p1_keywords = 'seg_word.txt'    str1 = '农农/陈利农/宝贝'    # model = gensim.models.Word2Vec.load('weibo.word2vec')    model = gensim.models.Word2Vec.load('zhiwiki_news.word2vec')    p1_vec = word2vec(p1_keywords, model,str1)

    str2='舒蔻 尤妮佳 买'

转载于:https://www.cnblogs.com/hapyygril/p/9982215.html

Wordvec_句子相似度相关推荐

  1. 自然语言处理(nlp)之词袋模型及句子相似度

    本博文将会介绍NLP中常见的词袋模型(Bag of Words)以及如何利用词袋模型来计算句子间的相似度(余弦相似度,cosine similarity).   首先,让我们来看一下,什么是词袋模型. ...

  2. LSTM模型在问答系统中的应用 2017-06-27 21:03 在问答系统的应用中,用户输入一个问题,系统需要根据问题去寻找最合适的答案。 1:采用句子相似度的方式。根据问题的字面相似度选择相似度最

    LSTM模型在问答系统中的应用 2017-06-27 21:03 在问答系统的应用中,用户输入一个问题,系统需要根据问题去寻找最合适的答案. 1:采用句子相似度的方式.根据问题的字面相似度选择相似度最 ...

  3. 基于GRU和am-softmax的句子相似度模型 | 附代码实现

    作者丨苏剑林 单位丨广州火焰信息科技有限公司 研究方向丨NLP,神经网络 个人主页丨kexue.fm 前言:搞计算机视觉的朋友会知道,am-softmax 是人脸识别中的成果.所以这篇文章就是借鉴人脸 ...

  4. 句子相似度--余弦相似度算法的实现

    1.余弦相似度 余弦距离,也称为余弦相似度,是用向量空间中两个向量夹角的余弦值作为衡量两个个体间差异的大小的度量.余弦值越接近1,就表明夹角越接近0度,也就是两个向量越相似,这就叫"余弦相似 ...

  5. TextRank算法原理和提取关键词的主要过程详解 计算句子相似度 计算句子重要性公式

    1.TextRank计算句子相似度和句子重要性的公式 2.TextRank算法提取关键词的过程 3.TextRank建立关键词无向图

  6. nlp自然语言处理中句子相似度计算

    在做自然语言处理的过程中,现在智能对话比较火,例如智能客服,智能家电,智能音箱等,我们需要获取用户说话的意图,方便做出正确的回答,这里面就涉及到句子相似度计算的问题,那么本节就来了解一下怎么样来用 P ...

  7. python根据词向量计算相似度_如何使用gensim的word2vec模型和python计算句子相似度...

    如何使用gensim的word2vec模型和python计算句子相似度 根据Gensim Word2Vec,我可以使用gensim包中的word2vec模型来计算2个单词之间的相似度. 例如 trai ...

  8. 【论文泛读85】基于上下文的句子相似度

    贴一下汇总贴:论文阅读记录 论文链接:<Sentence Similarity Based on Contexts> 一.摘要 现有的衡量句子相似度的方法面临两个挑战:(1)标记数据集通常 ...

  9. Tensorflow实例-CNN处理句子相似度(MPCNN)

    前两篇使用CNN处理句子相似度的文章,实际上使用了很简单的CNN模型,按照自己对CNN的理解实现了代码.完成以后,就开始翻阅论文,想了解一些经典的处理句子相似度的方法. 这篇文章 发表在仅次于ACL会 ...

  10. NLP之句子相似度之入门篇

    文章目录 1.基于统计的方法 1.1.编辑距离计算 1.2.杰卡德系数计算 1.3.TF 计算 1.4.TFIDF 计算 1.5.BM25 2.基于深度学习的方法 2.1.Word2Vec 计算 6. ...

最新文章

  1. 【MySQL】MySQL 如何实现 唯一随机数ID
  2. C# 监控统计 程序执行 时间
  3. mac mysql 报错_mac os mysql 配置?报错-问答-阿里云开发者社区-阿里云
  4. C#部分面试题及答案
  5. maven运行tomcat6出现错误Exception starting filter encodingFilter怎么解决
  6. desktop docker 无法卸载_在docker-for-desktop OSX上删除kubernetes集群
  7. 中断程序_91工控ABB机器人中断程序(陷阱程序)TRAP
  8. 胡巴小年调皮搞事情?嗨翻五城华为体验店
  9. Redis作为缓存服务器
  10. gis 六边形网格_ArcGIS中的奇技淫巧(Ⅱ)—蜂巢网格图
  11. 《银河英雄传说》杨威利经典语录2
  12. MySQL数据库对象
  13. 爆款养成思路,教你利用砍价做出刷屏活动!
  14. 第07章 文本信息提取
  15. 如何设置通过PMU的gpio来唤醒系统
  16. 强强联手 加速商用电脑技术革命
  17. 水牛城大学本科的计算机专业,PGA学生系列访谈(三):毕业生访谈之我在水牛城的大学时光...
  18. JVM笔记(三)类与类加载
  19. 干掉 Swagger (丝袜哥),试试这个新工具!
  20. 代码BUG之曲线救国

热门文章

  1. 【VRP】基于matlab遗传算法求解多中心的车辆路径规划问题【含Matlab源码 010期】
  2. joomla 3.6 mysql 版本_在RHEL,CentOS和Fedora上安装Joomla 3.6使用LAMP(Linux,Apache,MySQL,PHP)...
  3. 模拟tcp_TCP 半连接队列和全连接队列满了会发生什么?又该如何应对?
  4. html弧形列表效果,好看漂亮的html5网页特效学习笔记(5)_弧形菜单
  5. 【C++】常用查找算法
  6. python字典统计字母出现次数_第三篇 python运用字典统计字符串中字母出现的次数...
  7. cramer定理_线性代数部分重要定理总结
  8. mysql contain和like_mysql不带%的like 与等号之间的区别
  9. 把一个字符串分割成数组 php_php explode 将字符串分割为数组
  10. php+mysql事务处理例子详细分析实例