moytrage

urban_collect.pl

Mar 5th, 2012
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.61 KB | None | 0 0
  1. use strict;
  2. use warnings;
  3.  
  4. use URI::Escape;
  5. use JSON;
  6. use File::Path qw(make_path);
  7. use File::Copy qw(copy);
  8.  
  9. use IO::Handle qw();
  10. STDERR->autoflush(1);
  11.  
  12. sub json_unescape($) {
  13.     my $escaped = shift;
  14.     my $unescaped;
  15.     unless (eval { $unescaped = from_json("{\"term\":\"${escaped}\"}"); }) {
  16.         die "Can't unescape JSON [$escaped].";
  17.     } else { return $unescaped->{term}; }
  18. }
  19.  
  20. sub prepare_search_term($) {
  21.     my $term = shift;
  22.     $term =~ s/^\s+//g;
  23.     $term =~ s/\s+$//g;
  24.     return lc($term);
  25. }
  26.  
  27. my $time_start = time;
  28.  
  29. open my $fall, ">urban_all.txt" or die "Can't open urban_all.txt for writing.";
  30. binmode $fall;
  31.  
  32. my $overall_dups = 0;
  33. my $overall_unique = 0;
  34.  
  35. for my $char ('_', 'A'..'Z') {
  36.     print STDERR "[$char]  ";
  37.     my %entries;
  38.  
  39.     my $total = 0;
  40.  
  41.     open my $fdb, "<data/words/$char.txt" or die "Can't open [data/words/$char.txt] for reading.";
  42.     binmode $fdb;
  43.     while (<$fdb>) {
  44.         next if /^\s*$/;
  45.         my $line = $_;
  46.         chomp $line;
  47.         die "Can't parse line [$line]." unless ($line =~ /^{"query_term":"(.+?)","query_time":/);
  48.  
  49.         my $qt = prepare_search_term(json_unescape($1));
  50.  
  51.         $entries{$qt} = $line;
  52.         ++$total;
  53.     }
  54.     close $fdb;
  55.  
  56.     my $unique = scalar keys %entries;
  57.     my $dups = $total - $unique;
  58.  
  59.     $overall_dups += $dups;
  60.     $overall_unique += $unique;
  61.  
  62.     printf STDERR ("Unique: %6d  Dups: %6d\n", $unique, $dups);
  63.  
  64.     for my $qt (sort keys %entries) {
  65.         print $fall "$entries{$qt}\n";
  66.     }
  67. }
  68.  
  69. close $fall;
  70.  
  71. print STDERR "\n\nOverall Unique: $overall_unique, Overall Dups: $overall_dups\n";
  72.  
  73. my $time_end = time;
  74.  
  75. print STDERR "Total script running time: ".($time_end - $time_start)." sec.\n";
Advertisement
Add Comment
Please, Sign In to add comment