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

标签 python set intersection

我没有意识到 Python set 函数实际上将字符串分成单独的字符。我为 Jaccard 编写了 python 函数并使用了 python 交集方法。我将两个集合传递给此方法,在将这两个集合传递给我的 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 相似度。

最佳答案

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

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'])

关于Python:使用单词交集但不使用字符交集的 Jaccard 距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11911252/

相关文章:

python - Django Save 创建两条记录而不是一条

python - 使用 Tkinter 中的消息框显示哪个字段为空

c - C 中判断指针是否属于集合的最快方法是什么?

c++ - 用于整数下限和上限查询的快速数据结构?

c++ - 从鼠标坐标到 3d 的点-三角形相交?

python - django.urls.exceptions.NoReverseMatch : Reverse for 'sign_up' not found. 'sign_up' 不是有效的 View 函数或模式名称

node.js 中的 Python-Shell 未在 Systemd 服务中运行

c++ - 修改 C++ std::set 中元素的排序相关部分

python - 两个向量之间的numpy min()?

mongodb - (MongoDB) 在同一管道中结合并集和交集