0

すべて 1 行にあるテキスト ファイル内のパイプで区切られたエントリの数をカウントするスクリプトが必要です。行数をカウントするスクリプトを見つけて、それを機能させることができると考えて修正しましたが、残念ながらまだ行数をカウントしているため、現在は値を 1 に設定しています。テキスト ファイルは次のようになります。

Fred|Keith|Steve|James

私が試していたスクリプトはこれです:

$file1 = "names.txt";
$line = file($file1); 
$count = count(explode("|", $line));
echo "$file1 contains $count words";

どんな支援も大歓迎です。どうもありがとう。

4

4 に答える 4

1

このようなものには複数のアプローチ、ファイルを開くさまざまな方法、データを解釈するさまざまな方法があります。

ただし、次のようなものを探します。

<?php
    $data = file_get_contents("names.txt");
    $count = count(preg_split("/|/", $data));
    echo "The file contains $count words.";
?>
于 2012-12-04T23:53:22.590 に答える
1

最も速い方法は、パイプを数えて 1 つ追加することです。文字列をトリミングして、最初と最後のパイプがアイテムとしてカウントされないようにします。

<?php
   $contents = file_get_contents('names.txt');
   $count = substr_count(trim($contents, "|\n "), '|') + 1;
   echo "$file1 contains $count words";
于 2012-12-05T00:04:07.663 に答える
1

これを行う方法はたくさんありますが、これが私の見解です...

// get lines as array from file
$lines = file('names.txt');

// get a count for the number of words on each line (PHP > 5.3) 
$counts = array_map(function($line) { return count(explode('|', $line)); }, $lines);
// OR (PHP < 5.3) get a count for the number of words on each line (PHP < 5.3) 
//$counts = array_map(create_function('$line', 'return count(explode("|", $line));'), $lines);

// get the sum of all counts
$count = array_sum($counts);

// putting it all together as a one liner (PHP > 5.3)...
$count = array_sum(array_map(function($line) { return count(explode('|', $line)); }, file('names.txt')));
// or (PHP < 5.3)...
// $count = array_sum(array_map(create_function('$line', 'return count(explode("|", $line));'), file('names.txt')));
于 2012-12-05T00:10:27.907 に答える
0

あなたはほとんどそれをしました、どのように動作するかについての小さな誤解がありますfile:

line 変数には単一ではなくすべての行があり、0 から始まる数値インデックスを持つ単一の行にアクセスできます

$nunWords = count( explode ('|', $line[0] ) );

単語を数えるには、たとえば 10 行目でインデックスを 9 に変更するとします ( 0 から開始するため)。

もう一つの例

$lines = file ('yourfile');
foreach ( $lines as $curLine => $line )
{
      echo  "On line " . $curLine+1 . " we got " . count( explode ('|', $line ) ) . " words<br/>\n";
}
于 2012-12-05T00:14:34.683 に答える