alternate versions of the barcode collision handlers.. rebarcodes to migschema +...
[migration-tools.git] / elect_zips
1 #!/usr/bin/perl -w
2
3 # Copyright 2009-2012, Equinox Software, Inc.
4 #
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18
19 use strict;
20
21 my $VERSION = '1.00';
22
23 =pod
24
25 NAME
26
27         elect_zips - Utility to elect a winning city/state for each ZIP code based on patron data
28
29 USAGE
30
31         psql -U evergreen -A -t -F $'\t' -c 'SELECT city, state, post_code FROM actor.usr_address' > raw-csz.tsv
32         elect_zips < raw-csz.tsv > winning-zips.tsv
33
34 NOTES
35
36         Given input like "Miami Springs\tFL\t33166\n" derived from patron addresses,
37         this utility will print a city and state for each zip that has the maximum
38         number of occurrences. (It does not attempt to break ties. If there is a tie,
39         the city and state that reaches the maximum first will end up winning.)
40
41         You can also feed the output of elect_zips directly into I<enrich_zips --db US.txt --makezips>
42
43 =cut
44
45 my %zips;
46
47 # Go through the input and tally the city-state combinations for each ZIP code
48 while (<>) {
49         chomp;
50         (my $city, my $state, my $zip) = split(/\t/) or next;
51         next unless $zip =~ m/([\d]{5})/; # If it doesn't have 5 digits in a row, it's not a ZIP
52         $zip =~ s/^([\d]{5}).*$/$1/;      # We only want the 5-digit ZIP
53         $state = uc($state);
54         $city =~ s/^\s+//;
55         $city =~ s/\s+$//;
56         $zips{$zip}{"$city\t$state"}++;
57 }
58
59 # Pick and print a winner for each ZIP code
60 foreach(sort keys %zips) {
61         my $zip = $_;
62         my $max = 0;
63         my $citystate = "";
64         foreach(keys %{$zips{$zip}}) {
65                 if ($zips{$zip}{$_} > $max) {
66                         $max = $zips{$zip}{$_};
67                         $citystate = $_;
68                 }
69         }
70         print "$citystate\t$zip\n";
71 }