【问题标题】:How to use Word2Vec with two inputs in a loop?如何在循环中使用带有两个输入的 Word2Vec?
【发布时间】:2016-12-25 15:49:42
【问题描述】:

我正在尝试使用 word2vec 创建两个单词之间的相似性,我成功了,同时手动进行。但我有两个大的 txt 文件。我想创建一个循环。我尝试了几种循环方法,但没有成功。所以我决定请教专家。

我的代码:

import gensim

model = gensim.models.Word2Vec.load_word2vec_format('GoogleNews-vectors-negative300.bin', binary=True)
with open('myfile1.txt', 'r') as f:
    data1 = f.readlines()

with open('myfile2.txt', 'r') as f:
    data2 = f.readlines()

data = zip(data1, data2)

with open('myoutput.txt', 'a') as f:
    for x in data: 
        output = model.similarity(x[1], x[0])  # reading each word form each files
        out = '{} : {} : {}\n'.format(x[0].strip(), x[1].strip(),output)  
        f.write(out)

我的输入1,(文本1)

street 
spain 
ice
man

我的输入2(文本2)

florist
paris 
cold 
kid

我想要这个输出(output.txt)

street florist 0.19991447551502498
spain paris 0.5380033328157873
ice cold 0.40968857572410483
man kid  0.42953233870042506

【问题讨论】:

  • 请修复缩进和错误。
  • 我已经检查了你的代码,它正在工作!你面临的问题是什么?你有什么错误吗?
  • 我得到了这个错误:文件“testing1.py”,第 14 行,在 output = model.similarity(x[1], x[0]) # 从每个文件中读取每个单词文件“/anaconda2/lib/python2.7/site-packages/gensim-0.13.3-py2.7-linux-x86_64.egg/gensim/models/word2vec.py”,第 1598 行,相似返回点(matutils. unitvec(self[w1]), matutils.unitvec(self[w2])) 文件“anaconda2/lib/python2.7/site-packages/gensim-0.13.3-py2.7-linux-x86_64.egg/gensim/ models/word2vec.py",第 1578 行,在 getitem 中返回 self.syn0[self.vocab[words].index] KeyError: 'street \n'

标签: python nlp word2vec


【解决方案1】:
import gensim

model = gensim.models.Word2Vec.load_word2vec_format('GoogleNews-vectors-negative300.bin', binary=True)

 file1 = []
 file2 = []

 with open('myfile1.txt','rU') as f:
 for line in f:
 file1.append(line.rstrip())

 with open('myfile2.txt','rU') as f1:
 for line1 in f1:   
 file2.append(line1.rstrip())

 resutl=[]
 f=open('Output2.txt', "w") 
 for i in file1  :
 for g  in file2 :
        temp=[]
        temp.append(i)
        temp.append(g)
        w = model.similarity(i,g)
        temp.append(w)
        result=i+','+g+','+str(w)

        f.write(result)
        f.write('\n')

        f.close()

你的循环有问题,两个循环应该在一起。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-29
    • 2015-01-19
    • 1970-01-01
    • 2011-12-01
    • 2018-12-10
    • 1970-01-01
    • 2014-06-21
    相关资源
    最近更新 更多