| 1 | #!/usr/bin/perl | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | use Data::Dumper::Concise; | ||
| 7 | use HTML::TreeBuilder; | ||
| 8 | use Text::Trim qw/ trim /; | ||
| 9 | |||
| 10 | my $WIKIPEDIA_URL | ||
| 11 | = q{http://en.wikipedia.org/wiki/List_of_postcode_districts_in_the_United_Kingdom}; | ||
| 12 | |||
| 13 | my $html = HTML::TreeBuilder->new_from_url($WIKIPEDIA_URL); | ||
| 14 | |||
| 15 | my ($table) = $html->look_down( | ||
| 16 | _tag => 'table', | ||
| 17 | class => 'wikitable sortable' | ||
| 18 | ); | ||
| 19 | |||
| 20 | my ( undef, @rows ) = $table->look_down( _tag => 'tr' ); | ||
| 21 | |||
| 22 | my %districts; | ||
| 23 | |||
| 24 | foreach my $row (@rows) { | ||
| 25 | |||
| 26 | my ( $td_area, $td_districts, $td_post_town, $td_former_post_county ) | ||
| 27 | = $row->look_down( _tag => 'td' ); | ||
| 28 | |||
| 29 | my ($area) = $td_area->content_list; | ||
| 30 | |||
| 31 | ($area) = ( $td_area->look_down( _tag => 'a' ) )[0]->content_list | ||
| 32 | if ref $area; | ||
| 33 | |||
| 34 | next if $area eq 'BX'; # TODO handle BX non-geo codes | ||
| 35 | |||
| 36 | my ($post_town) | ||
| 37 | = ( $td_post_town->look_down( _tag => 'a' ) )[0]->content_list; | ||
| 38 | |||
| 39 | my @found; | ||
| 40 | foreach my $c ( $td_districts->content_list ) { | ||
| 41 | if ( ref $c ) { | ||
| 42 | next if $c->tag eq 'br'; | ||
| 43 | |||
| 44 | $found[-1]->{non_geographical} = 1 | ||
| 45 | if $c->attr('id') && $c->attr('id') eq 'ref_non-geo'; | ||
| 46 | |||
| 47 | } else { | ||
| 48 | |||
| 49 | foreach ( map {trim} split /,/, trim $c ) { | ||
| 50 | push @found, | ||
| 51 | { | ||
| 52 | district => $_, | ||
| 53 | non_geographical => 0, | ||
| 54 | post_town => $post_town | ||
| 55 | }; | ||
| 56 | } | ||
| 57 | |||
| 58 | } | ||
| 59 | } | ||
| 60 | |||
| 61 | foreach my $f (@found) { | ||
| 62 | my $district = $f->{district}; | ||
| 63 | |||
| 64 | my ( $area, $digits ) = $district =~ m{^([A-Z]+)(\d+)} | ||
| 65 | or die "can't parse district"; | ||
| 66 | |||
| 67 | $districts{$district} ||= { | ||
| 68 | district => $district, | ||
| 69 | area => $area, | ||
| 70 | digits => $digits, | ||
| 71 | post_town => [], | ||
| 72 | non_geographical => $f->{non_geographical}, | ||
| 73 | }; | ||
| 74 | |||
| 75 | push @{ $districts{$district}->{post_town} }, $f->{post_town}; | ||
| 76 | } | ||
| 77 | |||
| 78 | } | ||
| 79 | |||
| 80 | foreach my $district ( | ||
| 81 | sort { $a->{area} cmp $b->{area} || $a->{digits} <=> $b->{digits} } | ||
| 82 | values %districts ) | ||
| 83 | { | ||
| 84 | |||
| 85 | printf "%s,%d,%s\n", $district->{district}, | ||
| 86 | $district->{non_geographical}, | ||
| 87 | join( ',', @{ $district->{post_town} } ); | ||
| 88 | } | ||
| 89 | |||
| 90 | __END__ |