Home > Backend Development > PHP Tutorial > PHP implements a method to calculate the frequency of words in a file or array

PHP implements a method to calculate the frequency of words in a file or array

墨辰丷
Release: 2023-03-27 12:10:01
Original
1359 people have browsed it

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)
Copy after login

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 == &#39; &#39;) {
  $results[$word]++;
  $word = "";
 }
 else {
  $word .= $letter;
 }
}
fclose($handle);
print_r($results);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template