0

我有一些包含以下数据的文件。

示例文件 1:

sitename1,2009-07-19,"A1",11975,17.23
sitename1,2009-07-19,"A2",11,0.02
sitename1,2009-07-20,"A1",2000,17.23
sitename1,2009-07-20,"A2",538,0.02

我想将第 4 列中的值与第 2 列和第 3 列映射,如下所示。

需要输出。

Site,Type,2009-07-19,2009-07-20
sitename1,"A1",11975,2000
sitename1,"A2",11,538

这是我到目前为止所尝试的:

#! /usr/bin/perl -w
use strict;
use warnings;

my $column_header=["Site,Type"];
my $position={};
my $last_position=0;
my $current_event=[];

my $events=[];

while (<STDIN>) {
    my ($site,$date,$type,$value,$percent) = split /[,\n]/, $_;
    my $event_key = $date;

    if (not defined $position->{$event_key}) {
        $last_position+=1;
        $position->{$event_key}=$last_position;
        push @$column_header,$event_key;
    }
    my $pos = $position->{$event_key};
    if (defined $current_event->[$pos]) {
        dumpEvent();
    }
    if (not defined $current_event->[0]) {
        $current_event->[0]="$site,$type";
    }
    $current_event->[$pos]=$value;
}

dumpEvent();

 my $order = [];
 for (my $scan=0; $scan<scalar(@$column_header); $scan++) { 
    push @$order,$scan; 
}

printLine($column_header);
map { printLine($_) } @$events;

sub printLine {
    my $record=shift;

    my @result=();
    foreach my $offset (@$order) {
        if (defined $record->[$offset]) {
            push @result,$record->[$offset];
        } else {
            push @result,"";
        }
    }
    print join(",",@result)."\n";
}

sub dumpEvent {
    return unless defined $current_event->[0];
    push @$events,$current_event;
    $current_event=[];
}

我得到的输出如下。

*Site,Type,2009-07-19,2009-07-20*
sitename1,"A1",11975,
sitename1,"A2",11,
sitename1,"A1",,14620
sitename1,"A2",,538 
4

2 回答 2

1

如果我正确理解您(我不得不承认我只是在猜测),那么您在不同日期有几种类型的事物,并且每种事物都有一个值。因此,每个站点都需要一个像这样的散列数据结构:

$foo = {
    site  => 'sitename1',
    type  => 'A1',
    dates => [
                {
                    date  => '2009-07-19',
                    value => 11975,
                },
                {
                    date  => '2009-07-20',
                    value => 538,
                },
             ],
};

那甚至接近吗?

于 2009-07-28T09:38:31.930 回答
0

下面的代码产生了预期的结果并产生了“一些”意义。我不知道这是否真的有意义。

my %dates;
my %SiteType;
while (<DATA>) {
    chomp;
    my ($site,$date,$type,$value,$percent) = split /,/;
    $dates{$date} = '1';
    push @{$SiteType{"$site,$type"}}, $value ;
};
print 'Site,Type,', join(',', sort keys %dates), "\n";
foreach ( sort keys %SiteType) {
    print $_, ',', join(',', @{$SiteType{$_}}), "\n";
};
于 2009-07-28T11:15:06.307 回答