PHP中的字符串相似度:针对长字符串的类似Levenshtein的函数

8

PHP中的levenshtein函数适用于最大长度为255的字符串。有哪些好的替代方法可以计算PHP中句子的相似度得分。

基本上,我有一个句子数据库,我想找到近似重复的句子。similar_text函数没有给我预期的结果。有什么简单的方法可以检测类似下面的句子:

$ss="Jack is a very nice boy, isn't he?";
$pp="jack is a very nice boy is he";

$ss=strtolower($ss);  // convert to lower case as we dont care about case
$pp=strtolower($pp);

$score=similar_text($ss, $pp);
echo "$score %\n";  // Outputs just 29 %

$score=levenshtein ( $ss, $pp );
echo "$score\n";  // Outputs '5', which indicates they are very similar. But, it does not work for more than 255 chars :(

注意:我不关心语义意义。 - anon
3个回答

10

Levenshtein算法的时间复杂度为O(n*m),其中nm分别是两个输入字符串的长度。这相当昂贵,对于长字符串计算这样的距离将需要很长时间。

对于整个句子,您可能希望使用diff算法,例如: 在PHP中突出显示两个字符串之间的差异

话虽如此,PHP还提供了similar_text函数,其复杂度更高(O(max(n,m)**3)),但似乎适用于更长的字符串。


谢谢。你能告诉我是否错误地解释了similar_text的结果吗?我想要能够检测类似于示例中的相似句子。 - anon
similar_text 返回匹配字符的数量,而不是百分比。有一个第三个可选参数可以用来计算百分比。 - Spencer Hakim
哦,好的...我以为第三个参数只是用于传递结果变量的引用 :)。 - anon

4
我发现Smith Waterman Gotoh是比较句子的最佳算法。更多信息请参见此答案。以下是PHP代码示例:
class SmithWatermanGotoh 
{
    private $gapValue;
    private $substitution;

    /**
     * Constructs a new Smith Waterman metric.
     * 
     * @param gapValue
     *            a non-positive gap penalty
     * @param substitution
     *            a substitution function
     */
    public function __construct($gapValue=-0.5, 
                $substitution=null) 
    {
        if($gapValue > 0.0) throw new Exception("gapValue must be <= 0");
        //if(empty($substitution)) throw new Exception("substitution is required");
        if (empty($substitution)) $this->substitution = new SmithWatermanMatchMismatch(1.0, -2.0);
        else $this->substitution = $substitution;
        $this->gapValue = $gapValue;
    }

    public function compare($a, $b) 
    {
        if (empty($a) && empty($b)) {
            return 1.0;
        }

        if (empty($a) || empty($b)) {
            return 0.0;
        }

        $maxDistance = min(mb_strlen($a), mb_strlen($b))
                * max($this->substitution->max(), $this->gapValue);
        return $this->smithWatermanGotoh($a, $b) / $maxDistance;
    }

    private function smithWatermanGotoh($s, $t) 
    {   
        $v0 = [];
        $v1 = [];
        $t_len = mb_strlen($t);
        $max = $v0[0] = max(0, $this->gapValue, $this->substitution->compare($s, 0, $t, 0));

        for ($j = 1; $j < $t_len; $j++) {
            $v0[$j] = max(0, $v0[$j - 1] + $this->gapValue,
                    $this->substitution->compare($s, 0, $t, $j));

            $max = max($max, $v0[$j]);
        }

        // Find max
        for ($i = 1; $i < mb_strlen($s); $i++) {
            $v1[0] = max(0, $v0[0] + $this->gapValue, $this->substitution->compare($s, $i, $t, 0));

            $max = max($max, $v1[0]);

            for ($j = 1; $j < $t_len; $j++) {
                $v1[$j] = max(0, $v0[$j] + $this->gapValue, $v1[$j - 1] + $this->gapValue,
                        $v0[$j - 1] + $this->substitution->compare($s, $i, $t, $j));

                $max = max($max, $v1[$j]);
            }

            for ($j = 0; $j < $t_len; $j++) {
                $v0[$j] = $v1[$j];
            }
        }

        return $max;
    }
}

class SmithWatermanMatchMismatch
{
    private $matchValue;
    private $mismatchValue;

    /**
     * Constructs a new match-mismatch substitution function. When two
     * characters are equal a score of <code>matchValue</code> is assigned. In
     * case of a mismatch a score of <code>mismatchValue</code>. The
     * <code>matchValue</code> must be strictly greater then
     * <code>mismatchValue</code>
     * 
     * @param matchValue
     *            value when characters are equal
     * @param mismatchValue
     *            value when characters are not equal
     */
    public function __construct($matchValue, $mismatchValue) {
        if($matchValue <= $mismatchValue) throw new Exception("matchValue must be > matchValue");

        $this->matchValue = $matchValue;
        $this->mismatchValue = $mismatchValue;
    }

    public function compare($a, $aIndex, $b, $bIndex) {
        return ($a[$aIndex] === $b[$bIndex] ? $this->matchValue
                : $this->mismatchValue);
    }

    public function max() {
        return $this->matchValue;
    }

    public function min() {
        return $this->mismatchValue;
    }
}

$str1 = "Jack is a very nice boy, isn't he?";
$str2 = "jack is a very nice boy is he";
$o = new SmithWatermanGotoh();
echo $o->compare($str1, $str2);

我在两个大于100,000字节的字符串上尝试了你的代码,并在一个小时后中止。使用similar_text函数比较相同的字符串只需40秒。 - Jānis Elmeris

2
您可以尝试使用 similar_text 函数。
当字符数超过20,000个时,这个函数的速度会变得很慢(需要3-5秒),但是如果您只想比较句子的话,那么它仍能正常工作。
需要注意的是,当比较不同长度的字符串时,匹配度可能不会达到100%。例如,如果您将 "he" 与 "head" 进行比较,您只会得到一个50%的匹配度。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接