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

ドキュメントファイルがプレーンテキストであり、追加のマークアップが含まれていないと仮定すると、次のスクリプトを使用して、すべてのファイル内のすべての単語をカウントできます。

<?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))の単語数を取得できますが、これは単語ドキュメントでは機能しません。.doc ファイル形式を読み取ることができるライブラリまたは外部プログラムを見つける必要があります。

于 2009-11-20T05:13:38.440 に答える