Two new utilities that, together, can generate a zips.txt file customized for your...
[migration-tools.git] / elect_zips
1 #!/usr/bin/perl -w
2
3 use strict;
4
5 my $VERSION = '1.00';
6
7 =pod
8
9 NAME
10
11         elect_zips - Utility to elect a winning city/state for each ZIP code based on patron data
12
13 USAGE
14
15         psql -U evergreen -A -t -F $'\t' -c 'SELECT city, state, post_code FROM actor.usr_address' > raw-csz.tsv
16         elect_zips < raw-csz.tsv > winning-zips.tsv
17
18 NOTES
19
20         Given input like "Miami Springs\tFL\t33166\n" derived from patron addresses,
21         this utility will print a city and state for each zip that has the maximum
22         number of occurrences. (It does not attempt to break ties. If there is a tie,
23         the city and state that reaches the maximum first will end up winning.)
24
25         You can also feed the output of elect_zips directly into I<enrich_zips --db US.txt --makezips>
26
27 =cut
28
29 my %zips;
30
31 # Go through the input and tally the city-state combinations for each ZIP code
32 while (<>) {
33         chomp;
34         (my $city, my $state, my $zip) = split(/\t/) or next;
35         next unless $zip =~ m/([\d]{5})/; # If it doesn't have 5 digits in a row, it's not a ZIP
36         $zip =~ s/^([\d]{5}).*$/$1/;      # We only want the 5-digit ZIP
37         $state = uc($state);
38         $city =~ s/^\s+//;
39         $city =~ s/\s+$//;
40         $zips{$zip}{"$city\t$state"}++;
41 }
42
43 # Pick and print a winner for each ZIP code
44 foreach(sort keys %zips) {
45         my $zip = $_;
46         my $max = 0;
47         my $citystate = "";
48         foreach(keys %{$zips{$zip}}) {
49                 if ($zips{$zip}{$_} > $max) {
50                         $max = $zips{$zip}{$_};
51                         $citystate = $_;
52                 }
53         }
54         print "$citystate\t$zip\n";
55 }