【发布时间】:2016-10-26 23:55:19
【问题描述】:
我遇到了一个小错误,但我找不到它。我的目的是比较包含这些单词的文本文件。
secondly
pardon
woods
secondly
我编写了这样的脚本来比较这两个值:
secondly, pardon
secondly, woods
secondly, secondly
pardon, woods
pardon, secondly
woods, secondly
我的代码执行以下操作:
1) 如果单词相同,则得分为 1,否则为 gensim 向量模型计算的得分 2) 有一个计数器,当第一个 for 循环移动到下一个字时,计数器将复位。 eg, 其次, pardon > 其次, woods > 其次, 其次(此时计数为3)
代码
from __future__ import division
import gensim
textfile = 'businessCleanTxtUniqueWords'
model = gensim.models.Word2Vec.load("businessSG")
count = 0 # keep track of counter
score = 0
avgScore = 0
SentenceScore = 0
externalCount = 0
totalAverageScore = 0
with open(textfile, 'r+') as f1:
words_list = f1.readlines()
for each_word in words_list:
word = each_word.strip()
for each_word2 in words_list[words_list.index(each_word) + 1:]:
count = count + 1
try:
word2 = each_word2.strip()
print(word, word2)
# if words are the same
if (word == word2):
score = 1
else:
score = model.similarity(word,word2) # when words are not the same
# if word is not in vector model
except KeyError:
score = 0
# to keep track of the score
SentenceScore=SentenceScore + score
print("the score is: " + str(score))
print("the count is: " + str(count))
# average score
avgScore = round(SentenceScore / count,5)
print("the avg score: " + str(SentenceScore) + '/' + str(count) + '=' + str(avgScore))
# reset counter and sentence score
count = 0
SentenceScore = 0
错误信息:
Traceback (most recent call last):
File "C:/Users/User/Desktop/Complete2/Complete/TrainedTedModel/LatestJR.py", line 41, in <module>
avgScore = round(SentenceScore / count,5)
ZeroDivisionError: division by zero
('secondly', 'pardon')
the score is: 0.180233083443
the count is: 1
('secondly', 'woods')
the score is: 0.181432347816
the count is: 2
('secondly', 'secondly')
the score is: 1
the count is: 3
the avg score: 1.36166543126/3=0.45389
('pardon', 'woods')
the score is: 0.405021005657
the count is: 1
('pardon', 'secondly')
the score is: 0.180233083443
the count is: 2
the avg score: 0.5852540891/2=0.29263
('woods', 'secondly')
the score is: 0.181432347816
the count is: 1
the avg score: 0.181432347816/1=0.18143
我已将“from __future__ import division”包含在该部门中,但似乎无法修复它
我的文件可以在以下链接中找到:
Gensim 模型:
文本文件:
谢谢。
【问题讨论】:
-
count可能为零,因为您的第一个words_list[words_list.index(each_word) + 1:]可能为空。 -
嗨 kichik,我不太明白。你能解释一下吗?谢谢
-
您是否彻底检查过您的错误?它应该给出行号和错误代码的 sn-p。
-
嗨叶子,这是确切的错误消息。我是 python 新手,不知道如何调试好。
标签: python list python-2.7 divide-by-zero