1

2 つの文字列を比較する方法を探しています。しかし、単純な equals() ではありません。String に一致する可能性が高いことを示す指標が必要です。たとえば (値は計算されていない推測です):

"Car" と "Car" は 1.0 を返します

"Car dog" と "Car" は 0.5 を返します

"sitting" と "sit" は 0.45 などを返します。

基本的には、 Java 用のdifflib.sqeuencematcher ( http://docs.python.org/2/library/difflib.html ) の代替品です。

私はすでに@ java-diff-utilsを見ましたが、それを行う方法が見つかりませんでした....

4

2 に答える 2

2

求めているものに近い近似値を取得するには、文字列のサイズを取得してから StringUtils.remove 一致試行を使用し、元のサイズから残りのサイズを引いた値を元のサイズで割ります。

public double matchString(final String stringToMatch, final String matchPattern) {

    final int testSize = stringToMatch.length();


    if (testSize == 0 && matchPattern.length() == 0) {
        return 1.0;
    } else if (testSize == 0) {
        return 0.0;
    }

    final String remainderString = StringUtils.remove(stringToMatch, matchPattern);
    final int remainderSize = remainderString.length();

    final double result = (double) (testSize - remainderSize) / (double) testSize;

    return result;
}

@Test
public void testMatchString() {

    final double emptyResult = matchString("", "");

    final double delta = 0.01;
    Assert.assertEquals(1.0, emptyResult, delta);

    final double emptyCarResult = matchString("", "Car");
    Assert.assertEquals(0.0, emptyCarResult, delta);

    final double dogCatResult = matchString("CarDog", "Car");
    Assert.assertEquals(0.5, dogCatResult, delta);

    final double carResult = matchString("Car", "Car");
    Assert.assertEquals(1.0, carResult, delta);

    final double carsCarResult = matchString("Cars", "Car");
    Assert.assertEquals(0.75, carsCarResult, delta);

    final double sittingSitResult = matchString("Sitting", "Sit");
    Assert.assertEquals(0.4286, sittingSitResult, delta);

    // no match since the 'S' in Sitting is uppercased and is not in sit.
    // this can be fixed up lowercasing both the stringToMatch and matchPattern
    // in matchString
    final double sittingSit2Result = matchString("Sitting", "sit");
    Assert.assertEquals(0.0, sittingSit2Result, delta);

    // note the Sit match pattern matches two instences in 'Sit Sitting'
    final double sittingSit3Result = matchString("Sitter Sitting", "Sit");
    Assert.assertEquals(0.4286, sittingSit3Result, delta);
}
于 2013-05-21T15:01:27.587 に答える