0

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

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

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

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

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

4

4 回答 4

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,你可以参考readdirfile_get_contents的手册。

于 2009-11-20T05:03:30.927 回答
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";
?>
于 2009-11-20T05:07:36.437 回答
1

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

于 2009-11-20T05:27:46.880 回答
0

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

于 2009-11-20T05:13:38.440 回答