<?php
$_txts = array('1.txt','2.txt','3.txt');
$_len = count($_txts);
for ($i = 0;$i < $_len;$i++){
$_contents[] = file_get_contents($_txts[$i]);
}
for ($i = 0;$i < $_len;$i++){
//分词
$_words[] = explode(' ',trim($_contents[$i]));
foreach ($_words[$i] as $_key=>$_value){
$_value = trim($_value);
$_value = preg_replace('/[.|,|(|)|-|;]/','',$_value);
$_words[$i][$_key]=strtolower($_value);
}
//词频tf
$_tf[] = array_count_values($_words[$i]);
//去重
$_words[$i]= array_unique($_words[$i]);
}
//合并
$_words_com = array_merge($_words[0],$_words[1],$_words[2]);
//文档频率
$_df = array_count_values($_words_com);
//特征向量
for ($i = 0;$i < $_len;$i++){
$_vsm[$i] = $_df;
foreach($_vsm[$i] as $_key=>$_value){
$_vsm[$i][$_key] = 0;
}
for ($j=0;$j<count($_words[$i]);$j++){
if (in_array($_words[$i][$j],$_words_com)){
$_vsm[$i][($_words[$i][$j])] = ($_tf[$i][($_words[$i][$j])])*(log($_len/$_df[($_words[$i][$j])]));
}
}
}
for($i = 0;$i < count($_vsm); $i++){
echo '第'.($i+1).'篇文档的特征向量: ('. implode(",",$_vsm[$i]).')<br/>';
}
//测试
$_query = 'java';
$_vsm_que = $_df;
foreach($_vsm_que as $_key=>$_value){
$_vsm_que[$_key] = 0;
}
if (in_array($_query,$_vsm_que)){
$_vsm_que[$_query] = 1;
}
for ($i = 0; $i < count($_vsm); $i++){
foreach($_vsm_que as $_key=>$_value){
$_sim[$i] += ($_vsm[$i][$_key]) * ($_vsm_que[$_key]);
$_w1 += pow($_vsm_que[$_key],2);
$_w2 += pow($_vsm[$i][$_key],2);
}
//求夹角余弦值
$_cos[$i] = $_sim[$i]/(sqrt($_w1)*sqrt($_w2));
}
arsort($_cos);
foreach($_cos as $_key=>$_value){
echo '最符合的结果为第'.($_key+1).'篇文档';
break;
}
?>
转载于:https://blog.51cto.com/ufish/1381242