【问题标题】:How to find the most used word in a string PHP [duplicate]如何在字符串PHP中找到最常用的单词[重复]
【发布时间】:2017-02-28 15:02:13
【问题描述】:

我正在尝试在 PHP 中的字符串中查找最常用的单词。歌词文件是一串歌词。

            //display the most used word in the lyrics file
        $wordCount = str_word_count($lyrics);
        $wordCountArray = array();
        foreach($wordCount as $word){
            if(!array_key_exists($word, $wordCountArray)){
                $wordCountArray[$word] = 1;
            }else{
                $wordCountArray[$word] += 1;
            }
        }
        arsort($wordCountArray);
        print_r($wordCountArray[0]);

我收到此代码的错误,我想知道什么不起作用。我需要实际的单词而不是数字。

【问题讨论】:

  • 你有什么问题?
  • 这可能取决于$lyrics 是什么。您可能需要提供一个示例。
  • “我收到此代码错误” - 究竟是什么?你也得到了答案;看到那个。
  • 下面的答案是 undefined offset: 0

标签: php


【解决方案1】:

我想你的意思是:

$words = str_word_count($lyrics, 1)
foreach($words as $word) {

【讨论】:

    【解决方案2】:

    简单示例

    <?php
        $string = 'Hello hi hello abcd abc hoi bye hello';
    
        $string = strtolower($string);
        $words = explode(' ',$string);
        var_dump(array_count_values($words));
    

    【讨论】:

      猜你喜欢
      • 2020-04-26
      • 1970-01-01
      • 2015-12-28
      • 2014-12-14
      • 2019-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-27
      相关资源
      最近更新 更多