我正在尝试解析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:28:36
如果这是离题的,很抱歉,但是如果您在使用标准Unix文本处理工具的系统上,您可以使用此命令来计算字段#2中每个值出现的次数,并且不需要编写任何代码。
cut -d, -f2 filename.csv | sort | uniq -c这将生成类似如下的输出,其中首先列出计数,然后列出邮政编码:
12 12345
2 56789
34 78912
1 90210https://stackoverflow.com/questions/16628373
复制相似问题