5

我正在尝试使用Text::CSVPerl 模块来解析制表符分隔的文件。

我要解析的文件是:

#IGNORE COLUMN1 COLUMN2 COLUMN3 COLUMN4
ROW1    x   y   z   a
ROW2    b   c   d   
ROW3    w

请注意,该文件是制表符分隔的。该文件可能有N列和N行。此外,在 的情况下ROW2,它有第四个选项卡但没有值。的值ROW3之后没有制表符。即某些列可能有未定义的值或空白值。wCOLUMN1

到目前为止,我已经开始编写 Perl 脚本,但很早就开始尝试弄清楚如何编写代码来回答以下问题:

找出有多少ROWn。然后每次COLUMNn检查我是否有ROWn值。所以在这种情况下COLUMN2COLUMN3COLUMN4会有缺失值。

任何提示和指导都会有所帮助(我是 Perl 新手)。我查看了 CPAN Text::CSV 页面,但我无法解决这个问题。

#!/usr/bin/perl
use warnings;
use strict;
use v5.12;
use Text::CSV;

my $csv = Text::CSV->new ({
     escape_char         => '"',
     sep_char            => '\t',
     eol                 => $\,
     binary              => 1,
     blank_is_undef      => 1,
     empty_is_undef      => 1,
     });

open (my $file, "<", "tabfile.txt") or die "cannot open: $!";
while (my $row = $csv->getline ($file)) {
    say @$row[0];
}
close($file);
4

1 回答 1

1

一种方法,每行处理每个字段并在不是时增加一个计数器false

#!/usr/bin/env perl

use warnings;
use strict;
use Text::CSV_XS;

my (@col_counter); 
my ($line_counter, $r, $num_cols) = (0, 0, 0); 

open my $fh, '<', shift or die;

my $csv = Text::CSV_XS->new({
    sep_char => qq|\t|
});

while ( my $row = $csv->getline( $fh ) ) { 
    ## First row (header), get the number of columns.
    if ( $line_counter == 0 ) { 
        $num_cols = $#$row;
        next;
    }
    ## For each data row, traverse every column and increment a 
    ## counter if it has any value.
    for ( 1 .. $#$row ) { 
        ++$col_counter[ $_ ] if $row->[ $_ ];
    }   
}
continue {
    $line_counter++;
}

printf qq|Lines of file: %d\n|, $line_counter - 1;
## Check if any column has missing values. For each column compare the 
## number of lines read (substract 1 of header) with its counter. If they
## are different it means that the column had any row without value.
for my $i ( 1 .. $num_cols ) { 
    $r = $line_counter - 1 - (defined $col_counter[ $i ] ? $col_counter[ $i ] : 0); 
    if ( $r > 0 ) { 
        printf qq|Column %d has %d missing values\n|, $i, $r;  
    }   
}

使用您的示例数据,像这样运行它:

perl script.pl infile

这会产生:

Lines of file: 3
Column 2 has 1 missing values
Column 3 has 1 missing values
Column 4 has 2 missing values

更新:见评论。我反向查找不包含任何值的列,并将当前行号附加到数组中,并用于join提取所有行。

我改变了哪些部分?这里保存行号。

for ( 1 .. $num_cols ) { 
    push @{ $col_counter[ $_ ] }, $line_counter unless $row->[ $_ ];
}

在这里打印它们。您将需要评论旧的行为。

if ( defined $col_counter[ $i ] ) { 
    printf qq|Column %d has no value in lines %s\n|, $i, join q|,|, @{ $col_counter[ $i ] };
}

它产生:

Lines of file: 3
Column 2 has no value in lines 3
Column 3 has no value in lines 3
Column 4 has no value in lines 2,3
于 2013-10-12T18:54:49.137 回答