Count word frequency in a text? [duplicate]

风流意气都作罢 提交于 2019-11-27 16:35:07

问题


Possible Duplicate:
php: sort and count instances of words in a given string

I am looking to write a php function which takes a string as input, splits it into words and then returns an array of words sorted by the frequency of occurence of each word.

What's the most algorithmically efficient way of accomplishing this ?


回答1:


Your best bet are these:

  • str_word_count — Return information about words used in a string
  • array_count_values — Counts all the values of an array

Example

$words = 'A string with certain words occuring more often than other words.';
print_r( array_count_values(str_word_count($words, 1)) );

Output

Array
(
    [A] => 1
    [string] => 1
    [with] => 1
    [certain] => 1
    [words] => 2
    [occuring] => 1
    [more] => 1
    [often] => 1
    [than] => 1
    [other] => 1
)

marking CW because question is a duplicate of at least two other questions containing the same answer



来源:https://stackoverflow.com/questions/4670417/count-word-frequency-in-a-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!