【问题标题】:How can I get the length of the longest value in a CSV column?如何获取 CSV 列中最长值的长度?
【发布时间】:2021-06-18 13:06:18
【问题描述】:

我是 Perl 的新手。我卡在格式化和显示数据。我需要从 CSV 文件中读取数据并以正确的格式将其打印在屏幕上。每列的宽度由列中存在的元素的最大长度决定。

my $file = $ARGV[0] or die; 
open(my $data, '<', $file) or die; 
my $max = 0;

while (my $line = <$data>)  
{ 
    chomp $line; 


# Split the line and store it 
# inside the words array 
my @words = split ", ", $line;   
my @C = split( ",", $line);
#$max = length $C[1];
print ("%08c", "$C[2]\n");
for (my $i = 0; $i <= 2; $i++) 
{ 
    #print "$words[$i] "; 
} 
#print "\n"; 


} 



 print "maximum:max($max)\n";

【问题讨论】:

  • 你能展示一个输入样本和相应的预期输出吗?
  • 如果您在列中有各种元素,例如 {apple, bat, cat, dance} 现在所有元素的宽度应该等于跳舞长度,以便在终端上看起来正确。
  • 请用示例更新问题。

标签: csv perl


【解决方案1】:

专栏程序可以做到这一点(见https://unix.stackexchange.com/q/18861/12567):

$ column -t -s, input.csv
cat            wooly mammoth  lizard
kangaroo       dog            bird
grey squirrel  koala          sea otter

如果您想自己执行此操作,则需要查看所有值。

最简单的事情可能是通过两次。在第一遍中,您将获得每列的最大长度并将其存储在@longest 中。如果下一行在某一列中有更长的值,则在 @longest 中替换该值。最后,每列最长的长度在@longest

open my $fh, '<', 'input.csv' or die ...;

my $csv = Text::CSV_XS->new;

@longest;
while( my $row = $csv->getline( $fh ) ) {
    foreach my $i ( 0 .. $#$row ) {
        my $length = length $row->[$i];
        $longest[$i] = $length if $longest[$i] < $length;
        }
    }

完成后,您将再次遍历线条并使用这些宽度:

seek $fh, 0, 0; # back to beginning of file
my $template = join ' ', map "%-${_}s", @longest;
print "format: $template\n";

while( my $row = $csv->getline( $fh ) ) {
    printf "$template\n", @$row;
    }

【讨论】:

    猜你喜欢
    • 2012-10-15
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    • 2014-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    相关资源
    最近更新 更多