当前位置:首页 > PHP教程 > 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);

对于大文件,第二种方法比较快比较安全,不会引起内存异常。

ps:这里再为大家推荐2款非常方便的统计工具供大家参考使用:

在线字数统计工具:
http://tools.jb51.net/code/zishutongji

在线字符统计与编辑工具:
http://tools.jb51.net/code/char_tongji

更多关于php相关内容感兴趣的读者可查看本站专题:《php常用函数与技巧总结》、《php字符串(string)用法总结》、《php数组(array)操作技巧大全》、《php基本语法入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家php程序设计有所帮助。



【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!