比较字符串Javascript可能返回%of


82

我正在寻找一个JavaScript函数,该函数可以比较两个字符串并返回它们相似的相似性。我已经看过soundex,但这对于多单词字符串或非名称来说并不是很好。我正在寻找类似的功能:

function compare(strA,strB){

}

compare("Apples","apple") = Some X Percentage.

该函数可以使用所有类型的字符串,包括数字,多字值和名称。也许有一个我可以使用的简单算法?

Ultimately none of these served my purpose so I used this:

 function compare(c, u) {
        var incept = false;
        var ca = c.split(",");
        u = clean(u);
        //ca = correct answer array (Collection of all correct answer)
        //caa = a single correct answer word array (collection of words of a single correct answer)
        //u = array of user answer words cleaned using custom clean function
        for (var z = 0; z < ca.length; z++) {
            caa = $.trim(ca[z]).split(" ");
            var pc = 0;
            for (var x = 0; x < caa.length; x++) {
                for (var y = 0; y < u.length; y++) {
                    if (soundex(u[y]) != null && soundex(caa[x]) != null) {
                        if (soundex(u[y]) == soundex(caa[x])) {
                            pc = pc + 1;
                        }
                    }
                    else {
                        if (u[y].indexOf(caa[x]) > -1) {
                            pc = pc + 1;
                        }
                    }
                }
            }
            if ((pc / caa.length) > 0.5) {
                return true;
            }
        }
        return false;
    }

    // create object listing the SOUNDEX values for each letter
    // -1 indicates that the letter is not coded, but is used for coding
    //  0 indicates that the letter is omitted for modern census archives
    //                              but acts like -1 for older census archives
    //  1 is for BFPV
    //  2 is for CGJKQSXZ
    //  3 is for DT
    //  4 is for L
    //  5 is for MN my home state
    //  6 is for R
    function makesoundex() {
        this.a = -1
        this.b = 1
        this.c = 2
        this.d = 3
        this.e = -1
        this.f = 1
        this.g = 2
        this.h = 0
        this.i = -1
        this.j = 2
        this.k = 2
        this.l = 4
        this.m = 5
        this.n = 5
        this.o = -1
        this.p = 1
        this.q = 2
        this.r = 6
        this.s = 2
        this.t = 3
        this.u = -1
        this.v = 1
        this.w = 0
        this.x = 2
        this.y = -1
        this.z = 2
    }

    var sndx = new makesoundex()

    // check to see that the input is valid
    function isSurname(name) {
        if (name == "" || name == null) {
            return false
        } else {
            for (var i = 0; i < name.length; i++) {
                var letter = name.charAt(i)
                if (!(letter >= 'a' && letter <= 'z' || letter >= 'A' && letter <= 'Z')) {
                    return false
                }
            }
        }
        return true
    }

    // Collapse out directly adjacent sounds
    // 1. Assume that surname.length>=1
    // 2. Assume that surname contains only lowercase letters
    function collapse(surname) {
        if (surname.length == 1) {
            return surname
        }
        var right = collapse(surname.substring(1, surname.length))
        if (sndx[surname.charAt(0)] == sndx[right.charAt(0)]) {
            return surname.charAt(0) + right.substring(1, right.length)
        }
        return surname.charAt(0) + right
    }

    // Collapse out directly adjacent sounds using the new National Archives method
    // 1. Assume that surname.length>=1
    // 2. Assume that surname contains only lowercase letters
    // 3. H and W are completely ignored
    function omit(surname) {
        if (surname.length == 1) {
            return surname
        }
        var right = omit(surname.substring(1, surname.length))
        if (!sndx[right.charAt(0)]) {
            return surname.charAt(0) + right.substring(1, right.length)
        }
        return surname.charAt(0) + right
    }

    // Output the coded sequence
    function output_sequence(seq) {
        var output = seq.charAt(0).toUpperCase() // Retain first letter
        output += "-" // Separate letter with a dash
        var stage2 = seq.substring(1, seq.length)
        var count = 0
        for (var i = 0; i < stage2.length && count < 3; i++) {
            if (sndx[stage2.charAt(i)] > 0) {
                output += sndx[stage2.charAt(i)]
                count++
            }
        }
        for (; count < 3; count++) {
            output += "0"
        }
        return output
    }

    // Compute the SOUNDEX code for the surname
    function soundex(value) {
        if (!isSurname(value)) {
            return null
        }
        var stage1 = collapse(value.toLowerCase())
        //form.result.value=output_sequence(stage1);

        var stage1 = omit(value.toLowerCase())
        var stage2 = collapse(stage1)
        return output_sequence(stage2);

    }

    function clean(u) {
        var u = u.replace(/\,/g, "");
        u = u.toLowerCase().split(" ");
        var cw = ["ARRAY OF WORDS TO BE EXCLUDED FROM COMPARISON"];
        var n = [];
        for (var y = 0; y < u.length; y++) {
            var test = false;
            for (var z = 0; z < cw.length; z++) {
                if (u[y] != "" && u[y] != cw[z]) {
                    test = true;
                    break;
                }
            }
            if (test) {
    //Don't use & or $ in comparison
                var val = u[y].replace("$", "").replace("&", "");
                n.push(val);
            }
        }
        return n;
    }


我正在测试这一点,但仍然找不到理想的解决方案。打破这些的经典例子。说的问题是“前两位总统是谁?” 有人回答“ adams and Washington”。与“乔治·华盛顿·约翰·亚当斯”的字符串比较应该大约为50%。
布拉德·鲁德曼

oof,取决于jQuery?
肖恩·惠纳里

Answers:


135

这是一个基于Levenshtein距离的答案https://en.wikipedia.org/wiki/Levenshtein_distance

function similarity(s1, s2) {
  var longer = s1;
  var shorter = s2;
  if (s1.length < s2.length) {
    longer = s2;
    shorter = s1;
  }
  var longerLength = longer.length;
  if (longerLength == 0) {
    return 1.0;
  }
  return (longerLength - editDistance(longer, shorter)) / parseFloat(longerLength);
}

用于计算编辑距离

function editDistance(s1, s2) {
  s1 = s1.toLowerCase();
  s2 = s2.toLowerCase();

  var costs = new Array();
  for (var i = 0; i <= s1.length; i++) {
    var lastValue = i;
    for (var j = 0; j <= s2.length; j++) {
      if (i == 0)
        costs[j] = j;
      else {
        if (j > 0) {
          var newValue = costs[j - 1];
          if (s1.charAt(i - 1) != s2.charAt(j - 1))
            newValue = Math.min(Math.min(newValue, lastValue),
              costs[j]) + 1;
          costs[j - 1] = lastValue;
          lastValue = newValue;
        }
      }
    }
    if (i > 0)
      costs[s2.length] = lastValue;
  }
  return costs[s2.length];
}

用法

similarity('Stack Overflow','Stack Ovrflw')

返回0.8571428571428571


您可以在下面玩它:


对几个单词的改进:var same2 = function(s1,s2){var split1 = s1.split(''); var split2 = s2.split(''); var sum = 0; var max = 0; var temp = 0; for(var i = 0; i <split1.length; i ++){max = 0; for(var j = 0; j <split2.length; j ++){temp =相似度(split1 [i],split2 [j]); if(max <temp)max =温度; } console.log(max); sum + = max / split1.length; }返回总和;};
infinito84

@ overlord1234上面的方法是否适用于这样的字符串:9e27dbb9ff6eea70821c02b4457cbc6b7eb8e12a64f46c192c3a05f1bc1519acd101193dac157c6233d9d773f9b364ca210d6287f9efa00bfc656746782905be吗?
hyperfkcb

它确实适用于没有附加语义的字符串。请尝试并运行内联代码段(感谢David)。输入上述字符串时,得到的相似度为0.17857142857142858。
overlord1234年

@hyperfkcb他正在实现编辑距离算法,该算法计算错误位置(或多或少)中有多少个字符,因此为了计算百分比,他采用了更长的可能的编辑距离值(longerLength)并进行了操作(longerLength-editDistance)/更长的长度。
infinito84 '18

但是,它对于长字符串来说太慢了。
凌晨

16

这是一个非常简单的函数,可以进行比较并根据等效性返回百分比。尽管尚未针对所有可能的情况进行测试,但它可能会帮助您入门。

function similar(a,b) {
    var equivalency = 0;
    var minLength = (a.length > b.length) ? b.length : a.length;    
    var maxLength = (a.length < b.length) ? b.length : a.length;    
    for(var i = 0; i < minLength; i++) {
        if(a[i] == b[i]) {
            equivalency++;
        }
    }
    

    var weight = equivalency / maxLength;
    return (weight * 100) + "%";
}
alert(similar("test","tes"));   // 75%
alert(similar("test","test"));  // 100%
alert(similar("test","testt")); // 80%
alert(similar("test","tess"));  // 75%

7
问题是“ atest”和“ test”返回0%,我们知道这是不正确的。
peresisUser

8

使用库来实现字符串相似性对我来说就像是一种魅力!

这是示例-

var similarity = stringSimilarity.compareTwoStrings("Apples","apple");    // => 0.88

6
很好,除了stringSimilarity具有一个称为lodash的依赖项,该依赖项包含超过1000个文件放入项目中,以便获得字符串相似性。
GrumpyCrouton

2
是的,它是在本地添加软件包时发生的。但是,相反,我们可以使用CDN来减小包的大小。下面是CDN链接- jsdelivr.com/package/npm/lodash - jsdelivr.com/package/npm/string-similarity
图沙·Walzade

2
他们删除了大多数依赖项,包括lodash
Lovenkrands

7

我迅速写了一篇,可能足以满足您的目的:

function Compare(strA,strB){
    for(var result = 0, i = strA.length; i--;){
        if(typeof strB[i] == 'undefined' || strA[i] == strB[i]);
        else if(strA[i].toLowerCase() == strB[i].toLowerCase())
            result++;
        else
            result += 4;
    }
    return 1 - (result + 4*Math.abs(strA.length - strB.length))/(2*(strA.length+strB.length));
}

这对相同但不同大小写的字符(四分之一)的权重与完全不同或缺失的字符的权重相同。它返回0到1之间的数字,表示字符串相同。0表示它们没有相似之处。例子:

Compare("Apple", "Apple")    // 1
Compare("Apples", "Apple")   // 0.8181818181818181
Compare("Apples", "apple")   // 0.7727272727272727
Compare("a", "A")            // 0.75
Compare("Apples", "appppp")  // 0.45833333333333337
Compare("a", "b")            // 0

6
不太准确:Compare(“ Apple”,“ zApple”)= 0.07,而Compare(“ Apple”,“ Applez”)= 0.84
Kousha

3
@Kousha,位置好。“ Apple”和“ zApple”只有一个共同的字母(第二个字母p)。
保罗

2
@Paulpro Apple和zApple在逻辑上共有五个字母。这是您的实现错误。苹果,zApple,Applez相似。

2
@Kousha,根据该算法,zApple并不相似,因为它的位置很高。这不会使算法不正确。
保罗

8
@Paulpro:这不会使您的算法不正确,但是却不能很好地回答这个问题……
MarcoS

6

如何函数similar_textPHP.js库

它基于具有相同名称的PHP函数。

function similar_text (first, second) {
    // Calculates the similarity between two strings  
    // discuss at: http://phpjs.org/functions/similar_text

    if (first === null || second === null || typeof first === 'undefined' || typeof second === 'undefined') {
        return 0;
    }

    first += '';
    second += '';

    var pos1 = 0,
        pos2 = 0,
        max = 0,
        firstLength = first.length,
        secondLength = second.length,
        p, q, l, sum;

    max = 0;

    for (p = 0; p < firstLength; p++) {
        for (q = 0; q < secondLength; q++) {
            for (l = 0;
            (p + l < firstLength) && (q + l < secondLength) && (first.charAt(p + l) === second.charAt(q + l)); l++);
            if (l > max) {
                max = l;
                pos1 = p;
                pos2 = q;
            }
        }
    }

    sum = max;

    if (sum) {
        if (pos1 && pos2) {
            sum += this.similar_text(first.substr(0, pos2), second.substr(0, pos2));
        }

        if ((pos1 + max < firstLength) && (pos2 + max < secondLength)) {
            sum += this.similar_text(first.substr(pos1 + max, firstLength - pos1 - max), second.substr(pos2 + max, secondLength - pos2 - max));
        }
    }

    return sum;
}

1
是否根据匹配字符返回相似性?它如何评估相似性
hyperfkcb

2

查找两个字符串之间的相似度;我们可以使用一种或两种以上的方法,但我主要倾向于使用骰子系数。哪个更好!据我所知,比起使用Levenshtein距离

使用这种字符串相似性npm中的”包,您将可以按照我上面所说的进行工作。

一些简单的用法示例是

var stringSimilarity = require('string-similarity');

var similarity = stringSimilarity.compareTwoStrings('healed', 'sealed'); 

var matches = stringSimilarity.findBestMatch('healed', ['edward', 'sealed', 'theatre']);

有关更多信息,请访问上面给出的链接。谢谢。


1
欢迎使用指向解决方案的链接,但是请确保没有该链接的情况下,您的回答是有用的:在该链接周围添加上下文,以便您的其他用户可以了解它的含义和含义,然后引用您所使用页面中最相关的部分如果目标页面不可用,请重新链接。只是链接的答案可能会被删除
大卫·巴克

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.