我试图找出一个列表与另一个列表的相似性值。比如找到一个句子的jaccard相似度值。但这里唯一的区别是,如果值在两个列表的同一个索引中,那么它得到的是一个静态权重,否则它的权重将根据它离开该索引的位置来惩罚
a=["are","you","are","you","why"]
b=['you',"are","you",'are',"why"]
li=[]
va=[]
fi=[]
weightOfStatic=1/len(a)
for i in range(len(a)):
if a[i]==b[i]:
print("true1", weightOfStatic,a[i],b[i])
fi.append({"static":i, "dynamic":i,"Weight":weightOfStatic})
li.append([weightOfStatic,a[i],b[i]])
va.append(li)
else:
for j in range(len(b)):
if a[i]==b[j]:
weightOfDynamic = weightOfStatic*(1-(1/len(b))*abs(i-j))
fi.append({"static":i, "dynamic":j,"Weight":weightOfDynamic})
print("true2 and index diiference between words =%d"% abs(i-j),weightOfDynamic, i,j)
li.append([weightOfDynamic,a[i],b[j]])
va.append(weightOfDynamic)
sim_value=sum(va)
print("The similarity value is = %f" %(sim_value))
以下代码在没有重复单词的情况下运行良好。
比如a=[“你好”,“你在吗”,“你”]
b=[“你”,“是”,“如何”]。
对于这个意义,它给出了0.5的相似性值
上述示例的预期结果将介于列表A和B之间。如果列表A中的值有重复的单词,则该值应取其在B中最近的索引。这是如何为一个给定代码的示例进行匹配的
{'static': 0, 'dynamic': 1, 'Weight': 0.160}
here 0 should not match with 3 again
{'static': 0, 'dynamic': 3, 'Weight': 0.079}
{'static': 1, 'dynamic': 0, 'Weight': 0.160}
same for 1 and 2
{'static': 1, 'dynamic': 2, 'Weight': 0.160}
dynamic 1 is already overhere
{'static': 2, 'dynamic': 1, 'Weight': 0.160}
{'static': 2, 'dynamic': 3, 'Weight': 0.160}
dynamic 0 is already over
{'static': 3, 'dynamic': 0, 'Weight': 0.079}
{'static': 3, 'dynamic': 2, 'Weight': 0.160}
[0.2, 'why', 'why']
这里的重量是1.3200(重量从0到1)
结果应该是
{'static': 0, 'dynamic': 1, 'Weight': 0.160}
{'static': 1, 'dynamic': 0, 'Weight': 0.160}
{'static': 2, 'dynamic': 3, 'Weight': 0.160}
{'static': 3, 'dynamic': 2, 'Weight': 0.160}
[0.2, 'why', 'why']
总重量是0.84
首先,我“美化”了你的代码,让它看起来更像Python我觉得你有点过分复杂了。实际上,它甚至没有为我运行,因为你试图对一个包含int和list的列表求和
total_weight
变量来跟踪权重。然后我充分利用枚举函数,这样我就可以有索引和元素李>
a[3]
将匹配b[0]
,而不是更接近的b[2]
李>min(distance)
)这是我的示例输出:
我希望这有帮助
相关问题 更多 >
编程相关推荐