8f51a62b58ebe10b2d8ec5b56d16418b823dc017
[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         Add the --believegn flag if you want to believe the Geonames database when it conflicts with patron data.
24
25 =cut
26
27 my ($db, $makezips, %zips, $warn, $believegn);
28 my $result = GetOptions ("db=s"      => \$db,
29                          "makezips"  => \$makezips,
30                          "warn"      => \$warn,
31                          "believegn" => \$believegn);
32
33 die
34         "Please specify the location of the Geonames database with --db US.txt\n" .
35         "HINT: You can download it at http://download.geonames.org/export/zip/US.zip" .
36   "\n\nProgram halted"
37 unless defined($db);
38
39 open DB, $db or die "Couldn't open Geonames database $db: $!\n";
40
41 # Slurp in the Geonames database
42 while (<DB>) {
43         chomp;
44         my @f = split(/\t/);
45         @{$zips{$f[1]}} = @f[4,2,5];
46         # @{$zips{"33166"}} == ("FL", "Miami Springs", "Miami-Dade")
47 }
48
49 while (<>) {
50
51         chomp;
52         (my $city, my $state, my $zip) = split(/\t/) or next;
53         my $county = "";
54         my ($dbcity, $dbstate);
55
56         if (defined $zips{$zip}) {
57                 ($dbstate, $dbcity, $county) = @{$zips{$zip}};
58         } 
59
60         if ($warn) {
61                 if (!defined $zips{$zip}) {
62                         print STDERR "No county data found for ZIP code $zip ($city, $state)\n\n";
63                         next;
64                 }
65                 if ($city ne $dbcity || $state ne $dbstate) {
66                         print STDERR "Patron data input says $zip is $city, $state\n".
67                                      "Geonames database says $zip is $dbcity, $dbstate\n\n";
68                 }
69         }
70
71         if ($makezips) {
72                 if ($city ne $dbcity || $state ne $dbstate) {
73                         if ($believegn) {
74                                 $city = $dbcity;
75                                 $state = $dbstate;
76                         }
77                 }
78                 print "|" . join("|", ($state, $city, $zip, "1", "", $county)) . "||\n";
79         } else {
80                 print join("\t", ($city, $state, $zip, $county)) . "\n";
81         }
82 }