arrays - how to measure apperance frequency of words in a text with PHP -
this question has answer here:
given text (here, convenience, i've put text (text)file), want know how many time(s) each word appear in text.
php provides useful function : str_word_count
, which, $format
argument set 1
, returns simple array of words contained in $string
.
this code :
<?php $lines=array_map("findwords",file("words.txt")); $text=[]; foreach($lines $line) { $text=array_merge($text,$line); } $words=array_count_values($text); //order array values desc, preserving keys $words2=[]; ($i=0;$i<=count($words)-1;$i++) { $numof=max($words); $key=array_keys($words,$numof)[0]; $words2[$key]=$numof; unset($words[$key]); } echo '<pre>'; print_r($words2); echo '</pre>'; function findwords($str) { return str_word_count($str,1); }
Comments
Post a Comment