如何汇总列文本文件 [英] How to sum column text file

查看:106
本文介绍了如何汇总列文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我立即道歉,因为 我已经在站点上看到了多个线程,但是不幸的是,我的知识仍然不足以完成我的项目. 我有一个文本文件,我必须做每一列的总和(只需要总计):

Hello everyone and I immediately apologize, as I have seen various threads on the site, but unfortunately my knowledge is still insufficient to complete my project. I have a text file and I have to do the sum of each column (just need the total):

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 ...):

I need to get this(I have this file on linux then we can use 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号(此处无总和).

Where xxxx is the Id number (No sum here).

我一直在尝试在PHP和MySQL中执行此操作-到目前为止还算不上运气.

I've been trying to do this in PHP and MySQL -- No luck so far.

推荐答案

尝试类似的操作

$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()来清理每一行

also, you can sanitize each row by replacing array_sum() by array_map() wih a callback function

这篇关于如何汇总列文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆