duanouyong4228 2012-07-25 13:50
浏览 44
已采纳

字计数器:似乎没有给出我需要的输出(PHP)

here's the line of code that I came up with:

function Count($text)
        {    
            $WordCount = str_word_count($text);         

            $TextToArray = explode(" ", $text);
            $TextToArray2 = explode(" ", $text);

            for($i=0; $i<$WordCount; $i++)
            {
                $count = substr_count($TextToArray2[$i], $text);
            }
            echo "Number of {$TextToArray2[$i]} is {$count}";                                                   
        }

So, what's gonna happen here is that, the user will be entering a text, sentence or paragraph. By using substr_count, I would like to know the number of occurrences of the word inside the array. Unfortunately, the output the is not what I really need. Any suggestions?

  • 写回答

3条回答 默认 最新

  • dounai9592 2012-07-25 13:56
    关注

    I assume that you want an array with the word frequencies.

    First off, convert the string to lowercase and remove all punctuation from the text. This way you won't get entries for "But", "but", and "but," but rather just "but" with 3 or more uses.

    Second, use str_word_count with a second argument of 2 as Mark Baker says to get a list of words in the text. This will probably be more efficient than my suggestion of preg_split.

    Then walk the array and increment the value of the word by one.

    foreach($words as $word)
      $output[$word] = isset($output[$word]) ? $output[$word] + 1 : 1;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器