获取文件夹中所有文件的字数

时间:2009-11-20 05:00:25

标签: php file text-processing

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

这是我到目前为止提出的代码:

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

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

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

4 个答案:

答案 0 :(得分:3)

怎么样

$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,您可以参考readdir手册,file_get_contents

答案 1 :(得分:2)

假设 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";
?>

答案 2 :(得分:1)

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

答案 3 :(得分:0)

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

相关问题