无法使用Text :: CSV解析csv文件

时间:2012-06-05 16:29:13

标签: perl

我有这种格式的csv文件:

"Keyword"   "Competition"   "Global Monthly Searches"   "Local Monthly Searches (United States)"    "Approximate CPC (Search) - INR"

"kasperaky support" -0  -0  -0  -0

第一行是列标题。

我在Text :: CSV中尝试了大多数选项,但我无法提取字段。

这里sep_char =>' “

我最接近的是获得第一列的第一个单词(仅限“kasperaky”)。

我正在以这种方式创建对象(尝试各种设置时):

my $csv = Text::CSV->new ( { 
    binary => 1 ,
    sep_char=>' ',allow_loose_quotes=>0,quote_space=>0,quote_char          => '"',
    ,allow_whitespace    =>0, eol=>"\015\012"
     } ) 
                 or die "Cannot use CSV: ".Text::CSV->error_diag ();

4 个答案:

答案 0 :(得分:5)

您的CSV是以制表符分隔的。使用以下代码(测试代码以对照您的示例文件):

use strictures;
use autodie qw(:all);       # automatic error checking open/close
use charnames qw(:full);    # \N named characters
use Text::CSV qw();
my $csv = Text::CSV->new({
    auto_diag   => 2,       # automatic error checking CSV methods
    binary      => 1,
    eol         => "\N{CR}\N{LF}",
    sep_char    => "\N{TAB}",
}) or die 'Cannot use CSV: ' . Text::CSV->error_diag;

open my $fh, '<:encoding(ASCII)', 'computer crash.csv';
while (my $row = $csv->getline($fh)) {
    ...
}
close $fh;

答案 1 :(得分:4)

要称CSV文件有点拉伸!您的分隔符不是空格,它是一个包含1个或多个空格的序列,而Text :: CSV不处理该空格。 (不幸的是,当您的分隔符是空格时,allow_whitespace不起作用。)您可以使用以下内容:

use List::MoreUtils qw( apply );
my @fields = apply { s/\\(.)/$1/sg } $line =~ /"((?:[^"\\]|\\.)*)"/sg;

现在,如果这些是标签,那就是另一个故事,您可以使用sep_char => "\t"

答案 2 :(得分:1)

我总是建议使用解析器,通常Text :: CSV很棒,但是当你不使用真正的CSV时,它可能会很痛苦。在这种情况下,您可以尝试使用核心模块Text::ParseWords

这是我的例子。

#!/usr/bin/env perl

use strict;
use warnings;

use Text::ParseWords qw/parse_line/;

my @data;
while( my $line = <DATA> ) {
  chomp $line;
  my @words = parse_line( qr/\s+/, 0, $line );
  next unless @words;
  push @data, \@words;
}

use Data::Dumper;
print Dumper \@data;

__DATA__

"Keyword"   "Competition"   "Global Monthly Searches"   "Local Monthly Searches (United States)"    "Approximate CPC (Search) - INR"

"kasperaky support" -0  -0  -0  -0

此实现构建数据的2D数组,跳过未使用的行。当然,一旦解析了令牌,您就可以构建所需的任何数据结构。

$VAR1 = [
          [
            'Keyword',
            'Competition',
            'Global Monthly Searches',
            'Local Monthly Searches (United States)',
            'Approximate CPC (Search) - INR'
          ],
          [
            'kasperaky support',
            '-0',
            '-0',
            '-0',
            '-0'
          ]
        ];

答案 3 :(得分:0)

这对我来说有一个文件空间,分隔有一个或多个空格 这是Text :: CSV不能完成工作的情况......

open(my $data, '<:encoding(UTF-8)', $filename) or die "Cannot open $filename";

while( my $line = <$data> ) {
        my @fields = split(' ', $line);
        print "\n$line : $fields[0] --- $fields[1] ----- $fields[2]";

}