本文實例講述了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:2655101040 給予處理,謝謝支持。