我没有意识到Python set函数实际上将字符串分割成单独的字符。我为Jaccard编写了python函数,并使用了python相交方法。我向这个方法传递了两个集合,在将这两个集合传递给我的jaccard函数之前,我在setring上使用set函数。
例如:假设我有string 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),它会把string分成几个字符。所以当我把它发送到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相似度,而不是字符到字符的交集。
发布于 2012-08-11 10:01:35
请先尝试将字符串拆分为单词:
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'])发布于 2014-08-08 05:51:27
我的计算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发布于 2012-08-11 09:58:30
此属性不是集合所特有的:
>>> list('NEW Fujifilm')
['N', 'E', 'W', ' ', 'F', 'u', 'j', 'i', 'f', 'i', 'l', 'm']这里发生的事情是,字符串被视为可迭代序列,并被逐个字符地处理。
与set的情况相同:
>>> set('string')
set(['g', 'i', 'n', 's', 'r', 't'])要修复此问题,请在现有的set上使用.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()、元组、列表或其他可迭代对象,这样字符串就不会被视为可迭代对象:
>>> 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'])https://stackoverflow.com/questions/11911252
复制相似问题