這篇文章主要介紹了PHP編程計算檔案或數組中單詞出現頻率的方法,給出了2個統計單詞頻率的樣本,涉及php正則、數組操作及字串遍曆等相關技巧,需要的朋友可以參考下
本文執行個體講述了PHP編程計算檔案或數組中單詞出現頻率的方法。分享給大家供大家參考,具體如下:
如果是小檔案,可以一次性讀入到數組中,使用方便的數組計數函數進行詞頻統計(假設檔案中內容都是空格隔開的單詞):
<?php$str = file_get_contents("/path/to/file.txt"); //get string from filepreg_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 countarsort($words); //order from high to lowprint_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);
對於大檔案,第二種方法比較快比較安全,不會引起記憶體異常。