这是一个功能性的解决方案,仍然可以进行一些清理。我的一般算法是这样的:
- 将所有单词分解成一个列表w,去除多余的空格和标点符号
- 从偏移量 0 开始查找w的所有n长度块的数组
- 查找从偏移量 1 开始
的w的所有n长度块的数组
- ...继续,直到您找到从偏移量n -1开始的n长度块的数组
- 注意:如果w的最后一个块不是n长度,则不要将其包含在块数组中
- 将所有块数组连接为c
- 找出
c中每个值的频率
$sample = 'Lorem *ipsum* dolor sit amet, consectetur adipiscing elit. Nunc auctor urna sed urna mattis nec interdum magna ullamcorper. Donec ut lorem eros, id rhoncus nisl. Praesent sodales lorem vitae sapien volutpat et accumsan lorem viverra. Proin lectus elit, cursus ut feugiat ut, porta sit amet leo. Cras est nisl, aliquet quis lobortis sit amet, viverra non erat. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Integer euismod scelerisque quam, et aliquet nibh dignissim at. Pellentesque ut elit neque. Etiam facilisis nisl eu mauris luctus in consequat libero volutpat. Pellentesque auctor, justo in suscipit mollis, erat justo sollicitudin ipsum, in cursus erat ipsum id turpis. In tincidunt hendrerit scelerisque.';
function buildPhrases($string, $length) {
$onlyWords = preg_replace('/\p{P}/', '', $string);
$wordArray = preg_split('/\s+/s', $onlyWords);
function buildPhraseChunks($wordArray, $length, $offset = 0)
{
if ($offset >= $length) {
return array();
} else {
$offsetWordArray = array_slice($wordArray, $offset);
return array_merge(
array_chunk($offsetWordArray, $length),
buildPhraseChunks(
$wordArray, $length, $offset + 1
)
);
}
}
$onlyLengthN = function ($n) {
return function($a) use ($n) {
return count($a) == $n;
};
};
$concatWords = function ($a, $b) {
return $a . ' ' . $b;
};
$reduce = function ($a) use ($concatWords) {
return array_reduce($a, $concatWords);
};
$format = function ($a) {
return strtolower(trim($a));
};
$chunks = array_filter(
buildPhraseChunks($wordArray, $length),
$onlyLengthN($length)
);
$phrases = array_map($reduce, $chunks);
$formattedPhrases = array_map($format, $phrases);
return $formattedPhrases;
}
$phrases = buildPhrases($sample, 1);
$dropOnes = function($a) {
return $a != 1;
};
$freqCount = array_filter(
array_count_values($phrases),
$dropOnes
);
arsort($freqCount);
print_r($freqCount);