以下是一个简单的 PHP 方法,用于比较两个句子的相似度:

function compareSentences($sentence1, $sentence2) {
    // 将句子转换为小写并删除标点符号
    $sentence1 = strtolower(preg_replace('/[^a-zA-Z0-9\s]/', '', $sentence1));
    $sentence2 = strtolower(preg_replace('/[^a-zA-Z0-9\s]/', '', $sentence2));
    
    // 将句子拆分成单词
    $words1 = explode(' ', $sentence1);
    $words2 = explode(' ', $sentence2);
    
    // 获取所有单词的数量
    $totalWords = count(array_unique(array_merge($words1, $words2)));
    
    // 计算两个句子共同的单词数量
    $commonWords = count(array_intersect($words1, $words2));
    
    // 计算相似度百分比
    $similarity = ($commonWords / $totalWords) * 100;
    
    return $similarity;
}

使用示例:

$sentence1 = 'The quick brown fox jumps over the lazy dog';
$sentence2 = 'The quick brown dog jumps over the lazy fox';

$similarity = compareSentences($sentence1, $sentence2);

echo 'Similarity: ' . $similarity . '%';

输出结果:

Similarity: 66.666666666667%

该方法的基本思路是将句子转换为小写,并删除标点符号。然后将句子拆分成单词,并计算两个句子共同的单词数量。最后,将共同单词数量除以所有单词数量,得到相似度百分比。请注意,此方法仅用于简单的比较,不适用于所有情况。

php写一个模糊匹配句子意思是否相近的方法

原文地址: https://www.cveoy.top/t/topic/CRT 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录