Python:Jaccard使用单词交集但不是字符交集的距离

时间:2012-08-11 01:56:51

标签: python set intersection

我没有意识到Python设置函数实际上将字符串分成单个字符。我为Jaccard编写了python函数并使用了python intersection方法。我将两个集合传递给了这个方法,在将两个集合传递给我的jaccard函数之前,我在setring上使用了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))

如果我没有在我的字符串set上调用NEW Fujifilm 16MP 5x Optical Zoom Point and Shoot CAMERA 2 7 screen.jpg函数,则会收到以下错误:

    c = a.intersection(b)
AttributeError: 'str' object has no attribute 'intersection'

而不是字符到字符的交集,我想做单词到单词交集并获得jaccard相似性。

4 个答案:

答案 0 :(得分:9)

首先尝试将字符串拆分为单词:

word_set = set(your_string.split())

示例:

>>> word_set = set("NEW Fujifilm 16MP 5x".split())
>>> character_set = set("NEW Fujifilm 16MP 5x")
>>> word_set
set(['NEW', '16MP', '5x', 'Fujifilm'])
>>> character_set
set([' ', 'f', 'E', 'F', 'i', 'M', 'j', 'm', 'l', 'N', '1', 'P', 'u', 'x', 'W', '6', '5'])

答案 1 :(得分:7)

我计算Jaccard距离的函数:

def DistJaccard(str1, str2):
    str1 = set(str1.split())
    str2 = set(str2.split())
    return float(len(str1 & str2)) / len(str1 | str2)

>>> DistJaccard("hola amigo", "chao amigo")
0.333333333333

答案 2 :(得分:3)

此属性不是集独有的:

>>> list('NEW Fujifilm')
['N', 'E', 'W', ' ', 'F', 'u', 'j', 'i', 'f', 'i', 'l', 'm']

这里发生的是字符串被视为可迭代序列并逐字符处理。

你在set中看到同样的事情:

>>> set('string')
set(['g', 'i', 'n', 's', 'r', 't'])

要修复,请在现有集上使用.add(),因为.add()不使用interable:

>>> se=set()
>>> se.add('NEW Fujifilm 16MP 5x Optical Zoom Point and Shoot CAMERA 2 7 screen.jpg')
>>> se
set(['NEW Fujifilm 16MP 5x Optical Zoom Point and Shoot CAMERA 2 7 screen.jpg'])

或者,使用split(),元组,列表或某个替代的iterable,这样字符串就不会被视为可迭代的:

>>> set('something'.split())
set(['something'])
>>> set(('something',))
set(['something'])
>>> set(['something'])
set(['something'])

逐个字地添加更多基于字符串的元素:

>>> se=set(('Something',)) | set('NEW Fujifilm 16MP 5x Optical Zoom Point and Shoot CAMERA 2 7 screen.jpg'.split())   

或者,如果您在添加到集合时需要理解某些逻辑:

>>> se={w for w in 'NEW Fujifilm 16MP 5x Optical Zoom Point and Shoot CAMERA 2 7 screen.jpg'.split() 
         if len(w)>3}
>>> se
set(['Shoot', 'CAMERA', 'Point', 'screen.jpg', 'Zoom', 'Fujifilm', '16MP', 'Optical'])

现在你的工作方式如下:

>>> 'Zoom' in se
True
>>> s1=set('NEW Fujifilm 16MP 5x Optical Zoom Point and Shoot CAMERA 2 7 screen.jpg'.split())
>>> s2=set('Fujifilm Optical Zoom CAMERA NONE'.split())
>>> s1.intersection(s2)
set(['Optical', 'CAMERA', 'Zoom', 'Fujifilm'])

答案 3 :(得分:2)

这是我根据set function编写的那个 -

def jaccard(a,b):
    a=a.split()
    b=a.split()
    union = list(set(a+b))
    intersection = list(set(a) - (set(a)-set(b)))
    print "Union - %s" % union
    print "Intersection - %s" % intersection
    jaccard_coeff = float(len(intersection))/len(union)
    print "Jaccard Coefficient is = %f " % jaccard_coeff