【问题标题】:php: sort and count instances of words in a given stringphp:对给定字符串中单词的实例进行排序和计数
【发布时间】:2014-06-26 19:39:06
【问题描述】:

我需要帮助对字符串中单词的实例进行排序和计数。

假设我有一个关于单词的集合:

快乐美丽快乐线梨杜松子酒快乐线摇滚快乐线梨

如何使用php计算字符串中每个单词的每个实例并循环输出:

There are $count instances of $word

这样上面的循环就会输出:

happy 有 4 个实例。

有 3 行实例。

gin 有 2 个实例......

【问题讨论】:

    标签: php


    【解决方案1】:

    使用str_word_count()array_count_values() 的组合:

    $str = 'happy beautiful happy lines pear gin happy lines rock happy lines pear ';
    $words = array_count_values(str_word_count($str, 1));
    print_r($words);
    

    给予

    Array
    (
        [happy] => 4
        [beautiful] => 1
        [lines] => 3
        [pear] => 2
        [gin] => 1
        [rock] => 1
    )
    

    str_word_count() 中的 1 使函数返回一个包含所有找到的单词的数组。

    要对条目进行排序,请使用arsort()(它会保留键):

    arsort($words);
    print_r($words);
    
    Array
    (
        [happy] => 4
        [lines] => 3
        [pear] => 2
        [rock] => 1
        [gin] => 1
        [beautiful] => 1
    )
    

    【讨论】:

    • 如何将它与重音词一起使用?示例:重剑
    • 非常简单! ;) 谢谢!
    • @syfantid 是的,你说得很好,不需要其他答案;)
    【解决方案2】:

    试试这个:

    $words = explode(" ", "happy beautiful happy lines pear gin happy lines rock happy lines pear");
    $result = array_combine($words, array_fill(0, count($words), 0));
    
    foreach($words as $word) {
        $result[$word]++;
    }
    
    foreach($result as $word => $count) {
        echo "There are $count instances of $word.\n";
    }
    

    结果:

    There are 4 instances of happy.
    There are 1 instances of beautiful.
    There are 3 instances of lines.
    There are 2 instances of pear.
    There are 1 instances of gin.
    There are 1 instances of rock. 
    

    【讨论】:

      猜你喜欢
      • 2012-05-11
      • 1970-01-01
      • 2014-07-30
      • 2022-10-23
      • 1970-01-01
      • 2018-08-13
      • 1970-01-01
      • 1970-01-01
      • 2021-01-23
      相关资源
      最近更新 更多