琐碎知识点


相似度计算方法

<pre><code class="language-php">&lt;?php /** * Class LCS * 中文文本相似度比较 */ class LCS { var $str1; var $str2; var $c = array(); /*返回串一和串二的最长公共子序列*/ function getLCS($str1, $str2, $len1 = 0, $len2 = 0) { $this-&gt;str1 = $str1; $this-&gt;str2 = $str2; if ($len1 == 0) $len1 = strlen($str1); if ($len2 == 0) $len2 = strlen($str2); $this-&gt;initC($len1, $len2); return $this-&gt;printLCS($this-&gt;c, $len1 - 1, $len2 - 1); } /*返回两个串的相似度*/ function getSimilar($str1, $str2) { $len1 = strlen($str1); $len2 = strlen($str2); echo $this-&gt;getLCS($str1,$str2,$len1,$len2); die(); $len = strlen($this-&gt;getLCS($str1, $str2, $len1, $len2)); return $len * 2 / ($len1 + $len2); } function initC($len1, $len2) { //C -&gt; 二维数组 填满 (i*j) for ($i = 0; $i &lt; $len1; $i++) $this-&gt;c[$i][0] = 0; for ($j = 0; $j &lt; $len2; $j++) $this-&gt;c[0][$j] = 0; for ($i = 1; $i &lt; $len1; $i++) { for ($j = 1; $j &lt; $len2; $j++) { if ($this-&gt;str1[$i] == $this-&gt;str2[$j]) { $this-&gt;c[$i][$j] = $this-&gt;c[$i - 1][$j - 1] + 1; } else if ($this-&gt;c[$i - 1][$j] &gt;= $this-&gt;c[$i][$j - 1]) { $this-&gt;c[$i][$j] = $this-&gt;c[$i - 1][$j]; } else { $this-&gt;c[$i][$j] = $this-&gt;c[$i][$j - 1]; } } } } function printLCS($c, $i, $j) { if ($i == 0 || $j == 0) { if ($this-&gt;str1[$i] == $this-&gt;str2[$j]) return $this-&gt;str2[$j]; else return ""; } if ($this-&gt;str1[$i] == $this-&gt;str2[$j]) { return $this-&gt;printLCS($this-&gt;c, $i - 1, $j - 1).$this-&gt;str2[$j]; } else if ($this-&gt;c[$i - 1][$j] &gt;= $this-&gt;c[$i][$j - 1]) { return $this-&gt;printLCS($this-&gt;c, $i - 1, $j); } else { return $this-&gt;printLCS($this-&gt;c, $i, $j - 1); } } }</code></pre> <p>计算两个字符串的的最长公共长度</p>

页面列表

ITEM_HTML