js 文本相似度
function similar(s, t, f) { if (!s || !t) { return 0 } var l = s.length > t.length ? s.length : t.length var n = s.length var m = t.length var d = [] f = f || 3 var min = function(a, b, c) { return a < b ? (a < c ? a : c) : (b < c ? b : c) } var i, j, si, tj, cost if (n === 0) return m if (m === 0) return n for (i = 0; i <= n; i++) { d[i] = [] d[i][0] = i } for (j = 0; j <= m; j++) { d[0][j] = j } for (i = 1; i <= n; i++) { si = s.charAt(i - 1) for (j = 1; j <= m; j++) { tj = t.charAt(j - 1) if (si === tj) { cost = 0 } else { cost = 1 } d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost) } } let res = (1 - d[n][m] / l) return res.toFixed(f) } var s1 = similar('龙凤店','龙凤店') // 1 var s2 = similar('龙_神话与幻兽','龙凤店') // 0.1 var s1 = similar('龙_神话与幻兽','龙凤店') // 0.1 var s2 = similar('龙','龙_神话与幻兽') // 0.1 var s1 = similar('黑豹','龙') // 0 var s2 = similar('黑豹','黑豹') // 1 var s1 = similar('黑衣人3','黑豹'); // 0.2 var s2 = similar('黑衣人3','黑衣人3'); // 1
文章乃参考、转载其他博客所得,仅供自己学习作笔记使用!!!