doubi7346 2011-07-18 19:39
浏览 34
已采纳

PHP字长密度/计算字符串的计算

Given a text, how could I count the density / count of word lengths, so that I get an output like this

  • 1 letter words : 52 / 1%
  • 2 letter words : 34 / 0.5%
  • 3 letter words : 67 / 2%

Found this but for python

  • 写回答

4条回答 默认 最新

  • duanpang5583 2011-07-18 19:44
    关注

    You could start by splitting your text into words, using either explode() (as a very/too simple solution) or preg_split() (allows for stuff that's a bit more powerful) :

    $text = "this is some kind of text with several words";
    $words = explode(' ', $text);
    


    Then, iterate over the words, getting, for each one of those, its length, using strlen() ; and putting those lengths into an array :

    $results = array();
    foreach ($words as $word) {
        $length = strlen($word);
        if (isset($results[$length])) {
            $results[$length]++;
        }
        else {
            $results[$length] = 1;
        }
    
    }
    

    If you're working with UTF-8, see mb_strlen().


    At the end of that loop, $results would look like this :

    array
      4 => int 5
      2 => int 2
      7 => int 1
      5 => int 1
    


    The total number of words, which you'll need to calculate the percentage, can be found either :

    • By incrementing a counter inside the foreach loop,
    • or by calling array_sum() on $results after the loop is done.

    And for the percentages' calculation, it's a bit of maths -- I won't be that helpful, about that ^^

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 制裁名单20240508芯片厂商
  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接