Two new utilities that, together, can generate a zips.txt file customized for your...
[migration-tools.git] / enrich_zips
1 #!/usr/bin/perl -w
2
3 use strict;
4 use Getopt::Long;
5
6 my $VERSION = '1.01';
7
8 =pod
9
10 NAME
11
12         enrich_zips - Utility to add county information to city/state/ZIP data (and optionally use zips.txt format)
13
14 USAGE
15
16         enrich_zips --db US.txt < citystatezip.tsv
17         enrich_zips --makezips --db US.txt < citystatezip.tsv > zips.txt
18
19 NOTES
20
21         Geonames database can be downloaded from http://download.geonames.org/export/zip/US.zip
22
23 =cut
24
25 my ($db, $makezips, %zips, $warn);
26 my $result = GetOptions ("db=s"     => \$db,
27                          "makezips" => \$makezips,
28                          "warn"     => \$warn);
29 die
30         "Please specify the location of the Geonames database with --db US.txt\n" .
31         "HINT: You can download it at http://download.geonames.org/export/zip/US.zip" .
32   "\n\nProgram halted"
33 unless defined($db);
34
35 open DB, $db or die "Couldn't open Geonames database $db: $!\n";
36
37 # Slurp in the Geonames database
38 while (<DB>) {
39         chomp;
40         my @f = split(/\t/);
41         @{$zips{$f[1]}} = @f[4,2,5];
42         # @{$zips{"33166"}} == ("FL", "Miami Springs", "Miami-Dade")
43 }
44
45 while (<>) {
46
47         chomp;
48         (my $city, my $state, my $zip) = split(/\t/) or next;
49         my $county = "";
50         my ($dbcity, $dbstate);
51
52         if (defined $zips{$zip}) {
53                 ($dbstate, $dbcity, $county) = @{$zips{$zip}};
54         } 
55
56         if ($warn) {
57                 if (!defined $zips{$zip}) {
58                         print STDERR "No county data found for ZIP code $zip ($city, $state)\n\n";
59                         next;
60                 }
61                 if ($city ne $dbcity || $state ne $dbstate) {
62                         print STDERR "Patron data input says $zip is $city, $state\n".
63                                      "Geonames database says $zip is $dbcity, $dbstate\n\n";
64                 }
65         }
66
67         if ($makezips) {
68                 print "|" . join("|", ($state, $city, $zip, "1", "", $county)) . "||\n";
69         } else {
70                 print join("\t", ($city, $state, $zip, $county)) . "\n";
71         }
72 }