php文章相似性計算similar_text()函數升級

來源:互聯網
上載者:User

php預設有個函數similar_text()用於計算字串之間的相似性,該函數也可以計算兩個字串的相似性(以百分比計)。不過這個函數感覺對中文計算很不準確比如:

 代碼如下 複製代碼
echo similar_text("吉林禽業公司火災已致112人遇難","吉林寶源豐禽業公司火災已致112人遇難");

這兩個新聞標題其實都是一樣的,如果使用similar_text()相似對結果為:42,即只相似42%,所以這個感覺很不靠譜,今天剛好收集到一段PHP代碼也是用於比較兩個字串的相似性,直接貼出代碼:

 代碼如下 複製代碼

<?php
class LCS {
    var $str1;
    var $str2;
    var $c = array();
    /*返回串一和串二的最長公用子序列
*/
    function getLCS($str1, $str2, $len1 = 0, $len2 = 0) {
        $this->str1 = $str1;
        $this->str2 = $str2;
        if ($len1 == 0) $len1 = strlen($str1);
        if ($len2 == 0) $len2 = strlen($str2);
        $this->initC($len1, $len2);
        return $this->printLCS($this->c, $len1 - 1, $len2 - 1);
    }
    /*返回兩個串的相似性
*/
    function getSimilar($str1, $str2) {
        $len1 = strlen($str1);
        $len2 = strlen($str2);
        $len = strlen($this->getLCS($str1, $str2, $len1, $len2));
        return $len * 2 / ($len1 + $len2);
    }
    function initC($len1, $len2) {
        for ($i = 0; $i < $len1; $i++) $this->c[$i][0] = 0;
        for ($j = 0; $j < $len2; $j++) $this->c[0][$j] = 0;
        for ($i = 1; $i < $len1; $i++) {
            for ($j = 1; $j < $len2; $j++) {
                if ($this->str1[$i] == $this->str2[$j]) {
                    $this->c[$i][$j] = $this->c[$i - 1][$j - 1] + 1;
                } else if ($this->c[$i - 1][$j] >= $this->c[$i][$j - 1]) {
                    $this->c[$i][$j] = $this->c[$i - 1][$j];
                } else {
                    $this->c[$i][$j] = $this->c[$i][$j - 1];
                }
            }
        }
    }
    function printLCS($c, $i, $j) {
        if ($i == 0 || $j == 0) {
            if ($this->str1[$i] == $this->str2[$j]) return $this->str2[$j];
            else return "";
        }
        if ($this->str1[$i] == $this->str2[$j]) {
            return $this->printLCS($this->c, $i - 1, $j - 1).$this->str2[$j];
        } else if ($this->c[$i - 1][$j] >= $this->c[$i][$j - 1]) {
            return $this->printLCS($this->c, $i - 1, $j);
        } else {
            return $this->printLCS($this->c, $i, $j - 1);
        }
    }
}

$lcs = new LCS();
//返回最長公用子序列
$lcs->getLCS("hello word","hello china");
//返回相似性
echo $lcs->getSimilar("吉林禽業公司火災已致112人遇難","吉林寶源豐禽業公司火災已致112人遇難");同樣輸出結果為:0.90322580645161,明顯準確的多。


還有一種辦法就是利用分詞系統我們把標題分詞,然後再進行會更準確一些哦。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.