我没有意识到Python的set函数实际上会将字符串分成单个字符。我为Jaccard编写了一个Python函数,并使用了Python的交集方法。在将两个集合传递到我的jaccard函数之前,我在字符串集合上使用了set函数。
例如:假设我有字符串NEW Fujifilm 16MP 5x Optical Zoom Point and Shoot CAMERA 2 7 screen.jpg
,我会调用set(NEW Fujifilm 16MP 5x Optical Zoom Point and Shoot CAMERA 2 7 screen.jpg)
将字符串分解为字符。因此,当我将其传递给jaccard函数时,交集实际上是字符交集,而不是单词对单词的交集。如何进行单词对单词的交集?
#implementing jaccard
def jaccard(a, b):
c = a.intersection(b)
return float(len(c)) / (len(a) + len(b) - len(c))
如果我不在字符串 NEW Fujifilm 16MP 5x Optical Zoom Point and Shoot CAMERA 2 7 screen.jpg
上调用 set
函数,会得到以下错误:
c = a.intersection(b)
AttributeError: 'str' object has no attribute 'intersection'
我想进行词级别的交集运算并获取Jaccard相似度,而不是字符级别的交集。