当前位置:Gxlcms > PHP教程 > PHP实现计算文件或数组中单词出现频率的方法

PHP实现计算文件或数组中单词出现频率的方法

时间:2021-07-01 10:21:17 帮助过:2人阅读

这篇文章主要介绍了PHP实现计算文件或数组中单词出现频率的方法,给出了2个统计单词频率的示例,涉及php正则、数组操作及字符串遍历等相关技巧,需要的朋友可以参考下

具体如下:

如果是小文件,可以一次性读入到数组中,使用方便的数组计数函数进行词频统计(假设文件中内容都是空格隔开的单词):

  1. <?php
  2. $str = file_get_contents("/path/to/file.txt"); //get string from file
  3. preg_match_all("/\b(\w+[-]\w+)|(\w+)\b/",$str,$r); //place words into array $r - this includes hyphenated words
  4. $words = array_count_values(array_map("strtolower",$r[0])); //create new array - with case-insensitive count
  5. arsort($words); //order from high to low
  6. print_r($words)

如果是大文件,读入内存就不合适了,可以采用如下方法:

  1. <?php
  2. $filename = "/path/to/file.txt";
  3. $handle = fopen($filename,"r");
  4. if ($handle === false) {
  5. exit;
  6. }
  7. $word = "";
  8. while (false !== ($letter = fgetc($handle))) {
  9. if ($letter == ' ') {
  10. $results[$word]++;
  11. $word = "";
  12. }
  13. else {
  14. $word .= $letter;
  15. }
  16. }
  17. fclose($handle);
  18. print_r($results);

相关推荐:

php数组函数之array_unique()去除数组中重复值

php数组函数shuffle()与array_rand()随机函数使用步骤详解

php数组查找函数使用方法汇总

以上就是PHP实现计算文件或数组中单词出现频率的方法的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行