PHP词频统计方法概述
本示例详细解析了在PHP环境下,如何对文件内容或数组数据进行单词频次计算的实现方案。相关内容可供开发者参考并应用于实际项目中。
当处理规模较小的文件时,建议将其全部内容一次性加载到内存数组中。随后,利用PHP便捷的数组计数功能即可快速完成词频分析(前提是文件内的单词由空格分隔)。
<?php
$str = file_get_contents("/path/to/file.txt"); //get string from file
preg_match_all("/\b(\w+[-]\w+)|(\w+)\b/",$str,$r); //place words into array $r - this includes hyphenated words
$words = array_count_values(array_map("strtolower",$r[0])); //create new array - with case-insensitive count
arsort($words); //order from high to low
print_r($words)
若需处理体积庞大的文件,直接全量载入内存将导致资源消耗过大,此时应选用更为优化的处理逻辑:
<?php
$filename = "/path/to/file.txt";
$handle = fopen($filename,"r");
if ($handle === false) {
exit;
}
$word = "";
while (false !== ($letter = fgetc($handle))) {
if ($letter == ' ') {
$results[$word]++;
$word = "";
}
else {
$word .= $letter;
}
}
fclose($handle);
print_r($results);
在处理大型文件场景下,上述第二种方案不仅执行速度更快,而且能有效规避因内存不足引发的系统异常,具备更高的安全性。
补充说明:此处额外提供两款实用的统计辅助工具供各位参考选用:
在线字数统计服务: 点击使用
期望上述关于PHP程序设计的内容能为大家的工作带来实质性的帮助。