【问题标题】:Getting word count for all files within a folder获取文件夹中所有文件的字数
【发布时间】:2010-12-18 14:43:16
【问题描述】:

我需要查找文件夹中所有文件的字数。

这是我目前想出的代码:

$f="../mts/sites/default/files/test.doc";

// count words
$numWords = str_word_count($str)/11;
echo "This file have ". $numWords . " words";

这将计算单个文件中的单词,我将如何计算给定文件夹中所有文件的单词?

【问题讨论】:

  • @jakemcgraw:感谢重新编辑。
  • 0% 并且没有投票?你显然不在乎,我们为什么要关心?
  • @Mike:问题在于他还远远不能独自做到这一点!
  • @Lavanya,Mike B 说得有道理。也许你只是不明白这个网站是如何运作的,但你已经问了 19 个问题并且没有接受任何答案。至少这是非常粗鲁的。
  • 嘿,我不知道怎么投抱歉

标签: php file text-processing


【解决方案1】:

如果您使用 *nux,则可以使用 system('cat /tmp/* | wc -w')

【讨论】:

    【解决方案2】:

    您可以使用$words = str_word_count(file_get_contents($filepath)) 获取文本文件的字数,但这不适用于word 文档。您需要找到可以读取 .doc 文件格式的库或外部程序。

    【讨论】:

      【解决方案3】:

      假设 doc 文件是纯文本且不包含附加标记,您可以使用以下脚本计算所有文件中的所有单词:

      <?php
      $dirname = '/path/to/file/';
      $files = glob($dirname.'*');
      $total = 0;
      foreach($files as $path) {
          $count = str_word_count(file_get_contents($path));
          print "\n$path has $count words\n";
          $total += $count;
      }
      print "Total words: $total\n\n";
      ?>
      

      【讨论】:

        【解决方案4】:

        怎么样

        $array = array( 'file1.txt', 'file2.txt', 'file3.txt' );
        $result = array();
        foreach($array as $f ){
         $result[$f] = str_word_count(file_get_contents($f));
        }
        

        并使用目录

        if ($handle = opendir('/path/to/files')) {
            $result = array();
            echo "Directory handle: $handle\n";
            echo "Files:\n";
        
            /* This is the correct way to loop over the directory. */
            while (false !== ($file = readdir($handle))) {
               if($file == '.' || $file == '..')
                   continue;
               $result[$file] = str_word_count(file_get_contents('/path/to/files/' . $file)); 
               echo "This file {$file} have {$result[$file]} words";
            }
        
            closedir($handle);
        }
        

        Lavanya,你可以参考readdirfile_get_contents的手册。

        【讨论】:

        • @Rob:这是一个很好的评论,但他没有说那是 word 文件......让我们来看看他的评论。
        • 嗯,你是对的,我想我在他的帖子中看到了“word”和“doc”这两个词,我的大脑把它们放在了一起......
        • 让我们等一下……哎哟我累了!
        • 您好,您发送的代码非常好,我非常感谢您...reagards lavanya ks
        猜你喜欢
        • 1970-01-01
        • 2014-02-14
        • 2017-04-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-07
        • 2023-03-31
        • 2013-11-26
        相关资源
        最近更新 更多