如何对列文本文件求和

时间:2013-09-10 11:20:52

标签: php sql linux file text

大家好,我马上就道歉了 我在网站上看到了各种各样的主题,但不幸的是,我的知识仍不足以完成我的项目。 我有一个文本文件,我必须做每列的总和(只需要总数):

1003|name1|1208.00|2.00  |96.00  |0.00|0.00|0.00|0.00|98.00  |90.95  |7.05  |8516.40
1011|name2|1450.00|2.00  |49.00  |0.00|0.00|0.00|0.00|51.00  |44.62  |6.38  |9243.7
1004|name3|1450.00|25.00|170.00|0.00|0.00|0.00|0.00|195.00|175.75|19.25|27912.5 <br>
1002|name4|765.00 &nbsp;|1.00&nbsp;&nbsp;|17.00&nbsp; |0.00|0.00|0.00|0.00|18.00&nbsp; |15.13&nbsp; |2.87&nbsp; |2193.26

我需要得到这个(我在linux上有这个文件然后我们可以使用Bash,PHP,Mysql ......):

1003|name1|1208.00|2.00&nbsp;&nbsp;|96.00&nbsp; |0.00|0.00|0.00|0.00|98.00&nbsp; |90.95&nbsp; |7.05&nbsp; |8516.40
1011|name2|1450.00|2.00&nbsp;&nbsp;|49.00&nbsp; |0.00|0.00|0.00|0.00|51.00&nbsp; |44.62&nbsp; |6.38&nbsp; |9243.7
1004|name3|1450.00|25.00|170.00|0.00|0.00|0.00|0.00|195.00|175.75|19.25|27912.5 <br>
1002|name4|765.00 &nbsp;|1.00&nbsp;&nbsp;|17.00&nbsp; |0.00|0.00|0.00|0.00|18.00&nbsp; |15.13&nbsp; |2.87&nbsp; |2193.26 <br>
xxxx|Total&nbsp; |4873.00|30.00|332.00|0.00|0.00|0.00|0.00|362.00 |326.45|35.55|47865.86

其中xxxx是Id编号(此处不是总和)。

我一直在尝试用PHP和MySQL做到这一点 - 到目前为止没有运气。

4 个答案:

答案 0 :(得分:0)

伪代码:

open source file for reading
open destination file for writing
initialise totaling array to zero values
while not EOF
  read in line from file
  explode line into working array
  for x=2 ; x<14; x++ 
    add totalling array with floatval( working array )
    write line out to destination file
close read file
write out totals array to destination file
close destingation file

答案 1 :(得分:0)

尝试将文本文件数据放入Excel电子表格中,然后将列添加。

您可以使用VB将文本转换为excel,然后继续累加每列的值。

答案 2 :(得分:0)

1)替换所有| chars with,使用str_replace 2)使用str_getcsv从上面生成的csv字符串中创建数组 3)使用foreach并遍历每一行并计算总数

一些PHP代码

$str = file_get_contents('myfile.txt');
$str = str_replace('|', ',', $str);
$csv = str_getcsv($str);
$totals = array(0,0,0,0);
foreach ($csv as $row) {
    $totals[0] += trim($row[0]);
    $totals[1] += trim($row[2]);
    $totals[2] += trim($row[3]);
    $totals[3] += trim($row[4]);
}

$ totals数组包含所有总数!

答案 3 :(得分:0)

尝试类似:

$file = '/path/to/your_file.txt';
if ( ($file = fopen($file, "r")) !== FALSE) {
    $total = 0;
    $row_1 = 0;
    while (($line = fgetcsv($file, 1000, "|")) !== FALSE) {

        // brutal dirt sanitization
        foreach ( $line as $k => $v ) {
           $line[$k] = (float) preg_replace('#[^0-9\.]#','', $v);
        }

        $total = $total + array_sum(array_slice($line, 2));
        $row_1 = $row_1 + array_sum(array_slice($line, 2, 1));
        //...
    }
    echo $total.' | '.$row_1; //...
}
else echo 'error ...';

另外,您可以通过使用array_map()替换array_sum()并使用回调函数来清理每一行