从perl中的csv文件中删除额外的逗号

时间:2017-11-29 03:07:08

标签: perl csv

我有多个CSV文件,每个文件都有不同数量的条目,每个条目大约有300行。

每个文件的第一行是数据标签

    final JButton n15 = new JButton("=");
    n15.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String num1 = n15.getText();
            String global = t.getText();
            t.setText(global);
            ScriptEngineManager mgr = new ScriptEngineManager();
            ScriptEngine engine = mgr.getEngineByName("JavaScript");
            try {
                String s = global + " = " +engine.eval(global).toString();
                t.setText(s);
            } catch (ScriptException e1) {
                e1.printStackTrace();
            }
        }
    });

每个文件中的其余行包含数据

Person_id, person_name, person_email, person_address, person_recruitmentID, person_comments... etc

我想摆脱引号之间的逗号。 我目前正在阅读Text :: CSV文档,但这是一个缓慢的过程。

1 个答案:

答案 0 :(得分:1)

让我们解决这个问题: 您只能通过分割逗号来阅读CSV 。你刚刚说明了原因;逗号可能会被转义或在引号内。这些逗号完全有效,它们是数据的一部分。丢弃它们会破坏CSV中的数据。

出于这个原因以及其他原因,必须使用CSV解析库读取CSV文件。要查找哪些逗号是数据以及哪些逗号是结构,还需要使用CSV解析库解析CSV。因此,您不会通过尝试从引号内删除逗号来随时保存自己。相反,你会在修改数据的同时给自己更多的工作。您必须使用CSV解析库。

Text::CSV_XS是一个非常好,非常快的CSV解析库。它有很多功能,大部分都是你不需要的。幸运的是it has examples for doing most common actions

例如,以下是您从名为file.csv的文件中读取和打印每一行的方法。

use strict;
use warnings;
use autodie;
use v5.10;   # for `say`

use Text::CSV_XS;

# Open the file.
open my $fh, "<", "file.csv";

# Create a new Text::CSV_XS object.
# allow_whitespace allows there to be whitespace between the fields
my $csv = Text::CSV_XS->new({
    allow_whitespace => 1
});

# Read in the header line so it's not counted as data.
# Then you can use $csv->getline_hr() to read each row in as a hash.
$csv->header($fh);

# Read each row.
while( my $row = $csv->getline($fh) ) {
    # Do whatever you want with the list of cells in $row.
    # This prints them separated by semicolons.
    say join "; ", @$row;
}
相关问题