这篇文章主要介绍了php实现计算文件或数组中单词出现频率的方法,给出了2个统计单词频率的示例,涉及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免费学习笔记(深入)”;
<?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中文网其它相关文章!
                        
                        PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号