我正在尝试解析CSV文件以读取所有其他邮政编码。我正在尝试创建一个散列,其中每个键都是一个邮政编码,值是它在文件中出现的数字。然后我想把内容打印出来作为邮政编码。这是我到目前为止使用的Perl脚本。
use strict;
use warnings;
my %hash = qw (
zipcode count
);
my $file = $ARGV[0] or die "Need CSV file on command line \n";
open(my $data, '<', $file) or die "Could not open '$file $!\n";
while (my $line = <$data>) {
chomp $line;
my @fields = split "," , $line;
if (exists($hash{$fields[2]})) {
$hash{$fields[1]}++;
}else {
$hash{$fields[1]} = 1;
}
}
my $key;
my $value;
while (($key, $value) = each(%hash)) {
print "$key - $value\n";
}
exit;发布于 2013-05-19 04:12:09
您没有说明邮政编码在哪一列中,但是使用第三个字段检查现有的散列元素,然后使用第二个字段递增该元素。
不需要检查散列元素是否已经存在: Perl会很乐意地创建一个不存在的散列元素,并在您第一次访问它时将其递增到1。
也不需要显式地打开作为命令行参数传递的任何文件:如果您使用不带文件句柄的<>操作符,Perl将打开并读取它们。
对您自己的程序进行重新编写可能会起作用。它假定邮政编码在CSV的第二列中。如果它在其他地方,只需适当地更改++$hash{$fields[1]}即可。
use strict;
use warnings;
@ARGV or die "Need CSV file on command line \n";
my %counts;
while (my $line = <>) {
chomp $line;
my @fields = split /,/, $line;
++$counts{$fields[1]};
}
while (my ($key, $value) = each %counts) {
print "$key - $value\n";
}发布于 2013-05-19 04:28:36
如果这是离题的,很抱歉,但是如果您在使用标准Unix文本处理工具的系统上,您可以使用此命令来计算字段#2中每个值出现的次数,并且不需要编写任何代码。
cut -d, -f2 filename.csv | sort | uniq -c这将生成类似如下的输出,其中首先列出计数,然后列出邮政编码:
12 12345
2 56789
34 78912
1 90210https://stackoverflow.com/questions/16628373
复制相似问题