《PHP應(yīng)用:PHP編程計算文件或數(shù)組中單詞出現(xiàn)頻率的方法》要點:
本文介紹了PHP應(yīng)用:PHP編程計算文件或數(shù)組中單詞出現(xiàn)頻率的方法,希望對您有用。如果有疑問,可以聯(lián)系我們。
本文實例講述了PHP編程計算文件或數(shù)組中單詞出現(xiàn)頻率的方法.分享給大家供大家參考,具體如下:PHP學(xué)習(xí)
如果是小文件,可以一次性讀入到數(shù)組中,使用方便的數(shù)組計數(shù)函數(shù)進行詞頻統(tǒng)計(假設(shè)文件中內(nèi)容都是空格隔開的單詞):PHP學(xué)習(xí)
<?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)
如果是大文件,讀入內(nèi)存就不合適了,可以采用如下方法:PHP學(xué)習(xí)
<?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);
對于大文件,第二種方法比較快比較安全,不會引起內(nèi)存異常.PHP學(xué)習(xí)
PS:這里再為大家推薦2款非常方便的統(tǒng)計工具供大家參考使用:PHP學(xué)習(xí)
在線字?jǐn)?shù)統(tǒng)計工具:
http://tools.jb51.net/code/zishutongjiPHP學(xué)習(xí)
在線字符統(tǒng)計與編輯工具:
http://tools.jb51.net/code/char_tongjiPHP學(xué)習(xí)
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php常用函數(shù)與技巧總結(jié)》、《php字符串(string)用法總結(jié)》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語法入門教程》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》PHP學(xué)習(xí)
希望本文所述對大家PHP程序設(shè)計有所幫助.PHP學(xué)習(xí)
轉(zhuǎn)載請注明本頁網(wǎng)址:
http://www.snjht.com/jiaocheng/761.html