1

我有这样的数据:

Re: Building A

Month
kWh
1
100
2
110
3
105


Re: Building B

Month
kWh
1
200
2
210
3
205

我想将它转换为每个建筑物的多个文本文件。我的计划是:

  1. 提取建筑物分隔线之间的值
  2. 将行转换为表格

对于任务(1),我尝试像这样使用触发器运算符:

while( <DATA> ) {
  next unless /^Re: Building A/ .. /^Re: Building B/;
  my $line = $_;
  print $line;
}

但它不起作用,因为上面将只显示建筑物 A 的数据。这些数据是针对多个建筑物(其中大约 50 个)的,所以我需要在某种程度上递归地执行此操作。我还没有开始做任务(2)。

任何帮助将不胜感激。

4

3 回答 3

4

我会做这样的事情:

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

my %buildings;

while (<DATA>) {
    chomp;
    $buildings{$1} = [] if /^Re: Building ([AB])/;
    push @{$buildings{$1}}, $_ if $_;
}

while (my ($building, $data) = each %buildings) {
    open(my $out, '>', "$building.txt") or die "Unable to open file for writing: $!\n";

    for my $i (1 .. $#$data / 2) {
        print $out sprintf "%s\t%s\n", $data->[$i*2-1], $data->[$i*2];
    }
    close $out;
}

一个.txt:

Month   kWh
1       100
2       110
3       105

B.txt:

Month   kWh
1       200
2       210
3       205
于 2012-04-24T08:03:31.943 回答
2

我认为你可能会用一张桌子做得很好,所以我会告诉你如何做你要求的和我认为好的。

$name = "";
$data = {}; 
open(IN, "build.txt");
foreach my $line (<IN>){
    if($line =~ /Re: (.*)\n/) { # get building name
        $name = $1;
        $name =~ s/ /_/;
        $data->{$name} = []; # link to empty array
    } else {
        # make a new list and return to a list
        @{$data->{$name}} = (@{$data->{$name}}, $line); # add line to current building data
    }
}
close IN;
#
# write on file for each
#
foreach my $name (keys %{$data}){
    open(OUT, ">$name.txt");
    foreach my $line (@{$data->{$name}}){
        print OUT $line;
    }
    close OUT;
}
#
# or write into one file as a table
#
open(OUT, ">tabledata.txt");
foreach my $name (keys %{$data}){
    # because the data was not filtered on import we filter it now
    my $flag = 0;
    my @data; 
    foreach my $line (@{$data->{$name}}){
        if($line =~ /kWh/) {
            $flag = 1;
        } elsif($line =~ /^\n$/){ # skip blanks
        } elsif($flag == 1) {     # skip the counters
            $flag++; 
        } elsif($flag > 1) {
            chomp($line);
            @data = (@data, $line);
            $flag = 1;
        }   
    }
    # print pretty rows
    my $format = "%20s" . ("%10d" x @data);
    print OUT sprintf($format, $name, @data) . "\n";

}
close OUT;      

这会为每个建筑物创建一个带有建筑物名称的文件。Building_A.txt 的一个示例是:

Month
kWh
1
100
2
110
3
105

表文件名为 tabledata.txt,如下所示:

          Building_A       100       110       105
          Building_B       200       210       205
于 2012-04-24T07:07:43.487 回答
0

在 python 中,我会将文本文件解析为数据结构,然后使用asciitables输出它。理想情况下,您不会真正直接操作字符串,而是解析,然后显示为单独的操作。

您如何准确地进行解析取决于诸如文件格式的规则性以及您是否需要容忍文件中的错误或拼写错误等因素。

于 2012-04-24T03:53:42.680 回答