simhash php实现
SimHash 的 PHP 实现
SimHash 是一种用于文本相似度计算的算法,特别适用于大规模文档去重。以下是 PHP 实现 SimHash 的步骤和代码示例。
分词处理
使用 PHP 的分词扩展或简单正则分割文本为单词。若没有分词扩展,可通过空格和标点分割:

function tokenize($text) {
$text = preg_replace('/[^\p{L}\p{N}\s]/u', '', $text);
return preg_split('/\s+/', strtolower($text));
}
计算单词哈希值
对每个单词计算哈希值(如 CRC32 或 MD5)并转换为二进制字符串:
function getHashBinary($word) {
$hash = crc32($word);
return str_pad(decbin($hash), 32, '0', STR_PAD_LEFT);
}
加权与累加
为每个单词分配权重(如词频或 TF-IDF),并加权累加二进制位:

function computeWeightedBits($tokens) {
$vector = array_fill(0, 32, 0);
foreach ($tokens as $token) {
$hashBinary = getHashBinary($token);
for ($i = 0; $i < 32; $i++) {
$vector[$i] += ($hashBinary[$i] == '1') ? 1 : -1;
}
}
return $vector;
}
生成 SimHash
根据累加结果生成最终 SimHash 签名:
function generateSimHash($weightedVector) {
$simHash = '';
foreach ($weightedVector as $bit) {
$simHash .= ($bit > 0) ? '1' : '0';
}
return $simHash;
}
完整调用示例
$text = "This is a sample text for SimHash demonstration.";
$tokens = tokenize($text);
$weightedVector = computeWeightedBits($tokens);
$simHash = generateSimHash($weightedVector);
echo $simHash;
汉明距离计算
比较两个 SimHash 的相似度可通过汉明距离:
function hammingDistance($hash1, $hash2) {
$distance = 0;
for ($i = 0; $i < strlen($hash1); $i++) {
if ($hash1[$i] != $hash2[$i]) $distance++;
}
return $distance;
}
注意事项
- 哈希位数:示例使用 32 位,实际可根据需求调整(如 64 位)。
- 性能优化:对大文本需考虑分词效率和内存占用。
- 权重策略:默认权重为 1,可根据词频或 TF-IDF 调整。
此实现适用于基础文本去重任务,如需更高精度,可扩展为 64 位或引入更复杂的分词策略。






