This article mainly introduces the method of calculating the frequency of words in files or arrays in PHP. It gives 2 examples of counting word frequencies, involving PHP regularization, array operations, string traversal and other related skills. Friends in need You can refer to the following
for details:
If it is a small file, it can be read into the array at once and use the convenient array counting function for word frequency statistics (assuming that the contents in the file are all separated by spaces) Open words):
<?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)
If it is a large file, it is not appropriate to read it into the memory. You can use the following method:
<?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);
Related recommendations:
php array function array_unique() removes duplicate values from the array
php array function shuffle() and array_rand() random function usage steps detailed explanation
php array Summary of how to use the function
##
The above is the detailed content of PHP implements a method to calculate the frequency of words in a file or array. For more information, please follow other related articles on the PHP Chinese website!