use*_*135 5 regex perl parsing tab-delimited tab-delimited-text
我正在尝试使用Text::CSVPerl 模块来解析制表符分隔的文件。
我试图解析的文件是:
#IGNORE COLUMN1 COLUMN2 COLUMN3 COLUMN4
ROW1 x y z a
ROW2 b c d
ROW3 w
Run Code Online (Sandbox Code Playgroud)
请注意,该文件是制表符分隔的。该文件可能有N列和N行。此外,在 的情况下ROW2,它有第四个选项卡但没有值。ROW3的w值后没有选项卡COLUMN1。即某些列可能有未定义的值或空白值。
到目前为止,我已经开始编写 Perl 脚本,但很早就开始尝试弄清楚如何编写代码来回答以下问题:
找出ROWn有多少。然后每次COLUMNn检查我是否有ROWn值。所以在这种情况下COLUMN2,COLUMN3和COLUMN4会有缺失值。
任何提示和指导都会有所帮助(我是 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);
Run Code Online (Sandbox Code Playgroud)
一种方法是,每行处理每个字段,并在不是时增加一个计数器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;
}
}
Run Code Online (Sandbox Code Playgroud)
使用您的示例数据,运行它如下:
perl script.pl infile
Run Code Online (Sandbox Code Playgroud)
得出:
Lines of file: 3
Column 2 has 1 missing values
Column 3 has 1 missing values
Column 4 has 2 missing values
Run Code Online (Sandbox Code Playgroud)
更新:请参阅评论。我执行相反的操作,查找不包含任何值的列,并将当前行号附加到数组中,然后用于join提取所有行。
我改变了哪些部分?此处保存行号。
for ( 1 .. $num_cols ) {
push @{ $col_counter[ $_ ] }, $line_counter unless $row->[ $_ ];
}
Run Code Online (Sandbox Code Playgroud)
在这里打印它们。您将需要评论旧的行为。
if ( defined $col_counter[ $i ] ) {
printf qq|Column %d has no value in lines %s\n|, $i, join q|,|, @{ $col_counter[ $i ] };
}
Run Code Online (Sandbox Code Playgroud)
它产生:
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
Run Code Online (Sandbox Code Playgroud)