计算字符串相似度(编辑距离)
By
matresnan
at 2020-12-27 • 1人收藏 • 1712人看过
// 根据字符串编辑距离来实现功能 // 相关资料: // https://www.cnblogs.com/lishanyang/p/6016737.html // https://blog.csdn.net/xcxy2015/article/details/77164126 import console; function str_similarity(astr, bstr) begin var alen = string.len(astr) var blen = string.len(bstr) console.log('A字符串长度' + alen) console.log('B字符串长度' + blen) // 初始化二维数组 var dif = {} for(i = 0;alen;1){ var ydif = {} for(j = 0;blen;1){ if(j == 0){ table.insert(ydif, i, j) }elseif(i == 0){ table.insert(ydif, j, j) }else{ table.insert(ydif, -1, j) } } table.insert(dif, ydif, i) } // 判断距离 var temp, a, b, c for(i = 1;alen;1){ for(j = 1;blen;1){ if(string.charAt(astr,i) == string.charAt(bstr, j) ){ a = dif[i-1][j-1] b = dif[i-1][j] + 1 c = dif[i][j-1] + 1 }else { a = dif[i-1][j-1] + 1 b = dif[i-1][j] + 1 c = dif[i][j-1] + 1 } if(a > b){ if(b > c){ temp = c }else { temp = b } }elseif(a > c){ temp = c }else { temp = a } dif[i][j] = temp } } console.dumpTable(dif) // 计算字符串相似度 var similarity if(alen >= blen){ similarity = 1 - (dif[alen][blen] / alen) }else { similarity = 1 - (dif[alen][blen] / blen) } return similarity; end; var g = str_similarity("你好", "你好,aardio") console.log('两个字符串相似度为:' + g) console.pause()
登录后方可回帖