Count Word Frequency in Sentence - thoriqaziz.com

thoriqaziz.com

Do your hobby

Count Word Frequency in Sentence

Share This
Now, I wanna share how to count the frequency of the word in sentence in php. I also used this method when implement the Naïve Bayes Method in my research. This is the code “how to count word frequency in sentence.
<?php
function count_word_frequency($str,$word){
    $words = preg_split('/([\s\-_,:;?!\/\(\)\[\]{}<>\r\n"]|(?<!\d)\.(?!\d))/',$str);
    $count = 0;
    foreach($words as $key=>$value){
        if($value == $word){
                $count++;
        }
    }
    return $count;
}
?>


As we can seen that the function above use two parameters. That are $str (containt sentence) and $word (word which would be counted frequency in the $str). So, if you wanna try that function, you just call that function by type count_word_frequency(“YOUR_SENTENCE”, “YOUR_WORD”) in your code. Thank you!

No comments:

Post a Comment

Pages