时间:2021-07-01 10:21:17 帮助过:2人阅读
具体如下:
如果是小文件,可以一次性读入到数组中,使用方便的数组计数函数进行词频统计(假设文件中内容都是空格隔开的单词):
- <?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数组函数之array_unique()去除数组中重复值
php数组函数shuffle()与array_rand()随机函数使用步骤详解
php数组查找函数使用方法汇总
以上就是PHP实现计算文件或数组中单词出现频率的方法的详细内容,更多请关注Gxl网其它相关文章!