【问题标题】:PHP Counting delimited values in text file that are all on the same linePHP计算文本文件中所有在同一行上的分隔值
【发布时间】:2012-12-04 23:33:29
【问题描述】:

我需要一个脚本来计算文本文件中所有在一行上的管道分隔条目的数量。我找到了一个计算行数的脚本并对其进行了修改,以为我可以让它工作,但遗憾的是它仍然计算行数,所以目前将值设为 1。请你看看并帮助我解决问题吗?文本文件如下所示:

Fred|Keith|Steve|James

我尝试的脚本是这样的:

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

非常感谢任何帮助。 非常感谢。

【问题讨论】:

  • 这是转发吗?我似乎记得以前看到过这个确切的问题。同样的错误:“putputs”

标签: php file text count delimited


【解决方案1】:

最快的方法就是数一数管道并加一个。修剪字符串以确保开头和结尾的管道不计为一个项目。

<?php
   $contents = file_get_contents('names.txt');
   $count = substr_count(trim($contents, "|\n "), '|') + 1;
   echo "$file1 contains $count words";

【讨论】:

    【解决方案2】:

    这样的事情有多种方法,打开文件的方式不同,解释数据的方式也不同。

    但是,您将要寻找与此类似的东西:

    <?php
        $data = file_get_contents("names.txt");
        $count = count(preg_split("/|/", $data));
        echo "The file contains $count words.";
    ?>
    

    【讨论】:

      【解决方案3】:

      有很多方法可以做到这一点,这是我的看法...

      // 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')));
      

      【讨论】:

        【解决方案4】:

        你几乎做到了,只是对file的工作原理有一点误解:

        您的行变量中不是单行而是所有行,您可以访问数字索引从 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";
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-11-23
          • 2022-11-14
          • 1970-01-01
          • 1970-01-01
          • 2015-07-16
          • 2021-03-21
          • 2020-12-15
          • 1970-01-01
          相关资源
          最近更新 更多