Friday, May 31, 2013

Count Word Frequency in Sentence

Categories: ,

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!

Spread The Love, Share Our Article

Related Posts

No Response to "Count Word Frequency in Sentence"

Post a Comment