-
Notifications
You must be signed in to change notification settings - Fork 1
/
survey_parse_Survs.com_CSV-Num.perl
executable file
·2703 lines (2279 loc) · 73 KB
/
survey_parse_Survs.com_CSV-Num.perl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl
# survey_parse - parse results of survey from Survs.com in CSV format
#
# (C) 2008-2011, Jakub Narebski
#
# This program is licensed under the GPLv2 or later
#
# Parse result of exporting individual respondends (individual replies)
# in CSV format (Surveys > {survey} > Analyze > Export) from Survs.com,
# using 'Numeric' (shorter) format for responses
#
# It is intendend to parse results of "Git User's Survey 20xx"
use strict;
use warnings;
use Encode;
use IO::Handle;
use PerlIO::gzip;
use Text::CSV;
use Text::Wrap;
use Getopt::Long;
use Pod::Usage;
use List::Util qw(max maxstr min minstr sum);
use List::MoreUtils qw(uniq);
use Text::LevenshteinXS qw(distance);
use Term::ReadLine;
#use Term::ReadKey;
#use Term::ANSIColor;
use File::Spec;
use File::Basename;
use Date::Manip;
use Locale::Country;
use Locale::Object::Country;
use Statistics::Descriptive;
use constant DEBUG => 0;
# Storable uses *.storable, YAML uses *.yml
use Data::Dumper;
use Storable qw(store retrieve);
# YAML::Tiny has strange "'" escaping
#use YAML::Tiny qw(DumpFile LoadFile);
use YAML::Any qw(DumpFile LoadFile);
use utf8;
use open qw(:encoding(UTF-8) :std);
# ======================================================================
# ----------------------------------------------------------------------
my $survinfo_file = 'GitSurvey2011_questions.yml';
my $filename = 'Survey results Oct 03, 11.csv';
my $respfile = 'GitSurvey2011.responses.storable';
my $statfile = 'GitSurvey2011.stats.storable';
my $otherfile = 'GitSurvey2011.other_repl.yml'; # user-editable
my ($reparse, $restat);
my $resp_tz = "CET"; # timezone of responses date and time
my @special_columns = ( # are not about answers to questions
"Respondent Number",
"Date",
"Time",
"Channel"
);
my $nskip = scalar @special_columns;
# ask for categorizing even those response that match some rule
my $ask_categorized = 0;
my @country_names = all_country_names();
# 'text' or 'wiki' (actually anything or 'wiki')
my $format = 'text'; # default output format
# wiki table style
my $tablestyle = ' border="1" cellpadding="3" cellspacing="0"';
my %rowstyle =
('th' => 'font-weight: bold; background-color: #ffffcc;',
'row' => undef,
'footer' => 'font-weight: bold; font-style: italic; background-color: #ccffff;'
);
# default (minimum) width of column with answer
my $min_width = 30;
my $width = $min_width;
# vertical graphical histogram for 'wiki' format
my $show_graph = 1;
my $graph_color = '#ff0f0f';
my $graph_width = 200;
my $graph_units = 'px';
my @survey_data = ();
my %survey_data = @survey_data;
my @sections = ();
# ----------------------------------------------------------------------
# Extract column headers from CSV file, from first row
sub extract_headers_csv {
my ($csv, $fh) = @_;
seek $fh, 0, 0; # 0=SEEK_START; # rewind to start, just in case
my $row = $csv->getline($fh);
unless (defined $row) {
my $err = $csv->error_input();
print STDERR "$.: getline() failed on argument: $err\n" .
$csv->error_diag();
return;
}
return wantarray ? @$row : $row;
}
# Calculate staring column for each question
sub process_headers_csv {
my ($survinfo, $headers) = @_;
my @columns = @{$headers}[$nskip..$#$headers];
# calculate question to starting column number
my $qno = 0;
CSV_COLUMN:
for (my $i = 0; $i < @columns; $i++) {
my $colname = $columns[$i];
next unless ($colname =~ m/^Q(\d+)/);
if ($qno != $1) {
$qno = $1;
$survinfo->{"Q$qno"}{'col'} = $i;
}
}
}
# Handle special columns (number of response, date and time, channel)
sub responder_info_from_response {
my ($survinfo, $row) = @_;
my ($respno, $respdate, $resptime, $channel) = @$row;
my ($year, $day, $month) = split("/", $respdate);
$respdate = "$year-$month-$day"; # ISO format
my %info = (
'respondent number' => $respno,
'date' => $respdate,
'time' => $resptime,
'parsed_date' => ParseDate("$respdate $resptime $resp_tz"),
'channel' => $channel
);
return \%info;
}
# Extract info about given question from response
sub question_results_from_response {
my ($qinfo, $row) = @_;
my $col = $qinfo->{'col'} + $nskip; # column or starting column
# this if-elsif-else chain should be probably converted
# to dispatch table (might be not possible) or a switch statement
my %resp;
if ($qinfo->{'freeform'} ||
!exists $qinfo->{'codes'}) {
# free-form essay, single value or
# free-form text, single value
my $contents = $row->[$col];
%resp = (
'type' => $qinfo->{'freeform'} ? 'essay' : 'oneline',
'contents' => $contents
);
$resp{'skipped'} = 1
if ($contents eq '');
# free-form text, single value can be tabularized
# if it is not skipped
if (!exists $qinfo->{'codes'} &&
ref($qinfo->{'hist'}) eq 'CODE' &&
$contents ne '') {
%resp = (
%resp,
'original' => $contents,
'contents' => $qinfo->{'hist'}->($contents)
);
}
} elsif (!$qinfo->{'multi'} && !$qinfo->{'columns'}) {
# single choice
my $contents = $row->[$col];
my $other;
%resp = (
'type' => 'single-choice',
'contents' => $contents
);
if ($qinfo->{'other'}) {
$other = $row->[$col+1];
$resp{'other'} = $other
unless ($other eq '');
}
$resp{'skipped'} = 1
if ($contents eq '' &&
(!$qinfo->{'other'} || $other eq ''));
} elsif ($qinfo->{'multi'} && !$qinfo->{'columns'}) {
# multiple choice
my $skipped = 1;
%resp = (
'type' => 'multiple-choice',
'contents' => []
);
for (my $j = 0; $j < @{$qinfo->{'codes'}}; $j++) {
my $value = $row->[$col+$j];
next unless (defined $value && $value ne '');
if ($qinfo->{'other'} && $j == $#{$qinfo->{'codes'}}) {
$value = "".($j+1); # number stringified, not value !!!
}
push @{$resp{'contents'}}, $value;
$skipped = 0;
}
# multiple choice with other
if ($qinfo->{'other'}) {
my $other = $row->[$col+$#{$qinfo->{'codes'}}];
$resp{'other'} = $other if ($other ne '');
}
$resp{'skipped'} = 1 if ($skipped);
} elsif ($qinfo->{'columns'}) {
# matrix
my $skipped = 1;
%resp = (
'type' => 'matrix',
'contents' => []
);
for (my $j = 0; $j < @{$qinfo->{'codes'}}; $j++) {
my $value = $row->[$col+$j];
next unless (defined $value && $value ne '');
push @{$resp{'contents'}}, $value;
$skipped = 0;
}
$resp{'skipped'} = 1 if ($skipped);
} # end if-elsif ...
return \%resp;
}
# ......................................................................
# Parse data (given $filename CSV file)
sub parse_data {
my ($survinfo, $responses) = @_;
my $csv = Text::CSV->new({
binary => 1, eol => $/,
escape_char => "\\",
allow_loose_escapes => 1
}) or die "Could not create Text::CSV object: ".
Text::CSV->error_diag();
open my $fh, '<', $filename
or die "Could not open file '$filename': $!";
if ($filename =~ m/\.gz$/) {
binmode $fh, ':gzip:encoding(UTF-8)'
or die "Could not set up gzip decompression on '$filename': $!";
} else {
binmode $fh, ':encoding(UTF-8)';
}
# ........................................
# CSV column headers
my @headers = extract_headers_csv($csv, $fh);
process_headers_csv($survinfo, \@headers);
my $nfields = scalar(@headers);
# ........................................
# CSV lines
RESPONSE:
while (1) {
my $row = $csv->getline($fh);
last RESPONSE if (!defined $row && $csv->eof());
unless (defined $row) {
my $err = $csv->error_input();
print STDERR "$.: getline() failed on argument: $err\n";
$csv->error_diag(); # void context: print to STDERR
last RESPONSE; # error would usually be not recoverable
}
unless ($nfields == scalar(@$row)) {
print STDERR "$.: number of columns doesn't match: ".
"$nfields != ".(scalar @$row)."\n";
last RESPONSE; # error would usually be not recoverable
}
my $resp = [];
$resp->[0] = responder_info_from_response($survinfo, $row);
QUESTION:
for (my $qno = 1; $qno <= $survinfo->{'nquestions'}; $qno++) {
my $qinfo = $survinfo->{"Q$qno"};
next unless (defined $qinfo);
$resp->[$qno] = question_results_from_response($qinfo, $row);
} # end for QUESTION
#$responses->[$respno] = $resp
push @$responses, $resp
if (defined $resp && ref($resp) eq 'ARRAY' && @{$resp} > 0);
} # end while RESPONSE
return $responses;
}
# Parse CSV file, or retrieve serialized parsed data from file
sub parse_or_retrieve_data {
my $survey_data = shift;
my $responses = [];
my $what = 'responses';
local $| = 1; # autoflush
if (! -f $respfile) {
$filename .= '.gz'
unless -r $filename;
print STDERR "parsing '$filename'... ";
parse_data($survey_data, $responses);
print STDERR "(done)\n";
print STDERR "storing $what in '$respfile'... ";
store($responses, $respfile);
print STDERR "(done)\n";
} else {
print STDERR "retrieving $what from '$respfile'... ";
$responses = retrieve($respfile);
print STDERR "(done)\n";
}
return wantarray ? @$responses : $responses;
}
# ----------------------------------------------------------------------
# Make statistics
# Initialize structures for histograms of answers
sub prepare_hist {
my $survey_data = shift;
#Locale::Country::alias_code('uk' => 'gb');
QUESTION:
for (my $qno = 1; $qno <= $survey_data->{'nquestions'}; $qno++) {
my $q = $survey_data->{"Q$qno"};
next unless (defined $q);
next if (exists $q->{'histogram'});
if (exists $q->{'columns'}) {
# matrix
my $ncols = scalar @{$q->{'columns'}};
$q->{'histogram'} = {
map { $_ => [ (0) x $ncols ] }
@{$q->{'codes'}}
};
$q->{'matrix'} = {
map { $_ => { 'count' => 0, 'score' => 0 } }
@{$q->{'codes'}}
};
} elsif (exists $q->{'codes'}) {
$q->{'histogram'} = {
map { $_ => 0 } @{$q->{'codes'}}
}
} elsif (ref($q->{'hist'}) eq 'CODE') {
$q->{'histogram'} = {};
}
}
}
# Generate histograms of answers and responses
sub make_hist {
my ($survey_data, $responses) = @_;
my $nquestions = $survey_data->{'nquestions'};
# ...........................................
# Generate histograms of answers
RESPONSE:
foreach my $resp (@$responses) {
QUESTION:
for (my $qno = 1; $qno <= $nquestions; $qno++) {
my $qinfo = $survey_data->{"Q$qno"};
next unless (defined $qinfo);
my $qresp = $resp->[$qno];
# count non-empty / skipped responses
if ($qresp->{'skipped'}) {
add_to_hist($qinfo, 'skipped');
} else {
add_to_hist($qinfo, 'base');
}
# skip non-histogrammed questions, and skipped responses
next unless (exists $qinfo->{'histogram'});
next if ($qresp->{'skipped'});
# (perhaps replace this if-elsif chain by dispatch)
if ($qresp->{'type'} eq 'single-choice') {
add_to_hist($qinfo->{'histogram'},
$qinfo->{'codes'}[$qresp->{'contents'}-1]);
# something to do with other, if it is present, and used
# ...
} elsif ($qresp->{'type'} eq 'multiple-choice') {
add_to_hist($qinfo->{'histogram'},
map { $qinfo->{'codes'}[$_-1] } @{$qresp->{'contents'}});
# something to do with other, if it is present, and used
# ...
} elsif ($qresp->{'type'} eq 'matrix') {
for (my $i = 0; $i < @{$qresp->{'contents'}}; $i++) {
my $rowname = $qinfo->{'codes'}[$i];
my $column = $qresp->{'contents'}[$i];
$qinfo->{'histogram'}{$rowname}[$column-1]++;
# row score (columns as 1..N grade)
$qinfo->{'matrix'}{$rowname}{'count'} += 1;
$qinfo->{'matrix'}{$rowname}{'score'} += $column;
}
} elsif ($qresp->{'type'} eq 'oneline') {
add_to_hist($qinfo->{'histogram'}, $qresp->{'contents'});
}
} # end for $qno
} # end for $resp
# ...........................................
# Generate histogram of responsers (responses)
$survey_data->{'histogram'}{'skipped'} =
{ map { $_ => 0 } 0..$nquestions };
$survey_data->{'histogram'}{'date'} = {};
RESPONSE:
foreach my $resp (@$responses) {
my $nskipped = scalar grep { $_->{'skipped'} } @{$resp};
$resp->[0]{'nskipped'} = $nskipped; # !!!
#print "$resp->[0]{'respondent number'} skipped all questions\n"
# if $nskipped == $survey_data{'nquestions'};
add_to_hist($survey_data->{'histogram'}{'skipped'}, $nskipped);
add_to_hist($survey_data->{'histogram'}{'date'}, $resp->[0]{'date'})
if (defined $resp->[0]{'date'});
}
}
# Generate histograms of number of skipped questions
sub make_nskipped_stat {
my ($survey_data, $responses, $stat) = @_;
RESPONSE:
foreach my $resp (@$responses) {
my $nskipped =
defined $resp->[0]{'nskipped'} ? $resp->[0]{'nskipped'} :
scalar grep { $_->{'skipped'} } @{$resp};
$stat->add_data($nskipped);
}
}
# Generate histograms of answers, or retrieve it serialized from file
sub make_or_retrieve_hist {
my ($survey_data, $responses) = @_;
my $what = 'survey statistics';
local $| = 1; # autoflush
if (! -f $statfile) {
print STDERR "generating statistics... ";
prepare_hist($survey_data);
make_hist($survey_data, $responses);
print STDERR "(done)\n";
print STDERR "storing $what in '$statfile'... ";
store(extract_hist($survey_data), $statfile);
print STDERR "(done)\n";
} else {
print STDERR "retrieving $what from '$statfile'... ";
my $survey_hist = retrieve($statfile);
union_hash($survey_data, $survey_hist);
print STDERR "(done)\n";
}
return wantarray ? %$survey_data : $survey_data;
}
# extract histogram part of survey data (survey info)
# to store it in $statfile
sub extract_hist {
my $src = shift;
my $dst = {};
foreach my $key (keys %$src) {
my $val = $src->{$key};
if ($key =~ m/^(?: col | skipped | base | matrix | histogram )/x) {
$dst->{$key} = $val;
} elsif (ref($val) eq 'HASH') {
$val = extract_hist($val);
$dst->{$key} = $val if (%$val);
}
}
return $dst;
}
# overlay second hash over first, deeply (recursively)
# for putting retrieved histogram info in survey data structure
sub union_hash {
my ($base, $overlay) = @_;
foreach my $key (keys %$overlay) {
my $val = $overlay->{$key};
if (ref($val) eq 'HASH' &&
exists $base->{$key} &&
ref($base->{$key}) eq 'HASH') {
union_hash($base->{$key}, $val);
} else {
$base->{$key} = $val;
}
}
}
# ----------------------------------------------------------------------
# Analysis of 'other, please specify' responses
# Initialize / prepare data structure for storing information
# about 'other, please specify' answers and their categorization
sub init_other {
my ($survey_data) = @_;
my $nquestions = $survey_data->{'nquestions'};
my %other_repl;
QUESTION:
for (my $qno = 1; $qno <= $nquestions; $qno++) {
my $qinfo = $survey_data->{"Q$qno"};
next unless (defined $qinfo && $qinfo->{'other'});
my $ncols = 1;
$ncols = @{$qinfo->{'codes'}}
if (exists $qinfo->{'codes'} && $qinfo->{'multi'});
#print "Q$qno: col=$qinfo->{'col'}; ncols=$ncols\n";
$other_repl{"Q$qno"} = {
'title' => $qinfo->{'title'},
'col' => $qinfo->{'col'} + $ncols,
'repl' => [],
};
}
return wantarray ? %other_repl : \%other_repl;
}
# Initialize structure for analyzing 'other, please specify' answers,
# or retrieve it, serialized, from $otherfile
sub init_or_retrieve_other {
my ($survey_data) = @_;
my %other_repl;
my $what = "analysis of 'other' resp.";
local $| = 1; # autoflush
if (! -f $otherfile) {
print STDERR "initializing data for analysis of 'other' responses... ";
%other_repl = init_other($survey_data);
print STDERR "(done)\n";
print STDERR "storing $what in '$otherfile'... ";
DumpFile($otherfile, \%other_repl);
print STDERR "(done)\n";
} else {
print STDERR "retrieving $what from '$otherfile'... ";
my @entries = LoadFile($otherfile);
%other_repl = %{$entries[0]};
print STDERR "(done)\n";
}
return wantarray ? %other_repl : \%other_repl;
}
# Analyze (create categories) 'other, please specify' answers, interactively
sub make_other_hist {
my ($survey_data, $responses, $other_repl, $qno) = @_;
return unless -t STDOUT; # we need terminal for interactivity
if (!$qno || !$other_repl->{"Q$qno"}) {
#print Dumper($other_repl);
} else {
#print Dumper($other_repl->{"Q$qno"});
my $qinfo = $survey_data->{"Q$qno"};
my $orepl = $other_repl->{"Q$qno"};
my $term = Term::ReadLine->new('survey_parse');
$term->addhistory($_)
foreach (@{$qinfo->{'codes'}});
$term->MinLine(undef); # do not include anthing in history
my $respno = $orepl->{'last'} || 0;
my $nresponses = scalar @$responses;
my $new_rules = 0;
my $other_categorized = 0;
my $other_passed = 0;
my $other_skipped = 0;
# 'other, please specify' is always last code
my $other_all = $qinfo->{'histogram'}{$qinfo->{'codes'}[-1]};
$orepl->{'skipped'} = 0
if (exists $orepl->{'skipped'} && !$orepl->{'last'});
if ($respno < $nresponses) {
print fmt_question_title($qinfo->{'title'});
print question_type_description($qinfo)."\n\n";
}
my $skip_asking = 0;
RESPONSE:
for ( ; $respno < $nresponses; $respno++) {
my $resp = $responses->[$respno];
my $qresp = $resp->[$qno];
next if ($qresp->{'skipped'});
next unless ($qresp->{'other'});
my $other = $qresp->{'other'};
$other_passed++;
print "----- [$resp->[0]{'date'}] $respno / $nresponses ".
"$other_passed / $other_all\n";
if ($qresp->{'contents'}) {
if (ref($qresp->{'contents'}) eq 'ARRAY') {
# multiple-choice
print ">>".$qinfo->{'codes'}[$_-1]."\n"
foreach (@{$qresp->{'contents'}});
} else {
# single choice
print "#>".$qinfo->{'codes'}[$qresp->{'contents'}-1]."\n";
}
}
print "$other\n";
my @categories =
categorize_response($orepl->{'repl'}, $respno, $other);
my $matched = scalar @categories;
$other_categorized++ if $matched;
if ($matched && !$ask_categorized) {
update_other_hist($orepl, $qinfo, $qresp, @categories);
next RESPONSE;
}
if ($matched && $ask_categorized) {
print "c>$_\n" foreach (@categories);
}
my $rule = ''; # default is skip response
$rule = ask_rules($term, $respno, $other)
unless $skip_asking;
if (!defined $rule) {
$other_skipped = "all from $respno";
last RESPONSE;
}
if (!$rule) {
$other_skipped++;
next RESPONSE;
}
if ($rule eq 'passthrough') {
$other_skipped++;
$skip_asking = 1;
next RESPONSE;
}
$other_categorized++;
push @{$orepl->{'repl'}}, $rule;
push @categories, $rule->{'category'}
if exists $rule->{'category'};
$new_rules++;
update_other_hist($orepl, $qinfo, $qresp, @categories);
} # RESPONSE
$orepl->{'last'} = $respno;
$orepl->{'skipped'} ||= $other_skipped
if ($other_skipped);
print "Finished at response $respno of $nresponses\n"
if ($respno < $nresponses);
print "There were ".(scalar @{$orepl->{'repl'}})." rules ".
"(including $new_rules new rules)\n"
if (scalar @{$orepl->{'repl'}});
print "There were $other_categorized categorized out of ".
"$other_passed passed, out of $other_all together\n";
print "Skipped $other_skipped responses\n"
if $other_skipped;
#print Dumper($orepl);
# if there were new rules, or we updated histogram
# if ($new_rules)
{
local $! = 1; # autoflush
print STDERR "storing new rules and histogram in '$otherfile'... ";
DumpFile($otherfile, $other_repl);
print STDERR "(done)\n";
}
}
}
# given REPLACEMENTS (rules), RESPONSE_NUMBER and ANSWER,
# return list of categories ANSWER belongs to
sub categorize_response {
my ($repl_rules, $respno, $answer) = @_;
my @categories;
RULE:
for (my $i = 0; $i < @$repl_rules; $i++) {
my $rule = $repl_rules->[$i];
my ($regex, $val) = @$rule{'match','category'};
if (defined $regex && $answer =~ /$regex/) {
print "* /$regex/ matched => '$val'\n";
push @categories, $val;
} elsif (defined($rule->{'respno'}) &&
$rule->{'respno'} == $respno) {
print "* response number [$respno] => '$val'\n";
push @categories, $val;
}
} # end RULE
return uniq sort @categories;
}
# interactive, returns a rule
# return values:
# * () / undef - skip all
# * '' - skip response
# * one of the following kind of rules:
# - { 'match' =>regexp, 'category'=>category }
# - { 'respno'=>number, 'category'=>category }
sub ask_rules {
my ($term, $respno, $answer) = @_;
my ($matched, $rule);
print "Give regexp ".
"(or '.' to match line,".
" or RET to skip reply,". # " or / to autoskip,".
" or ^D to skip all):\n";
TRY: {
do {
$rule = $term->readline('INPUT> ');
if (!defined $rule) {
# ^D = EOF to skip all
print "\n. stop analysis (skip all)\n";
return;
}
if ($rule eq '') {
# RET to skip response
print "+ skipping '$answer'\n";
return '';
}
if ($rule eq '/') {
# RET to skip response
print "+ skipping all answers\n";
return 'passthrough';
}
if ($rule eq '.') {
#print "+ [$respno] is '$answer'\n";
$rule = $respno;
$matched = 'respno';
} elsif ($answer =~ /$rule/) {
#print "+ /$regex/ matched '$answer'\n";
$matched = 'match';
} else {
print "- /$rule/ didn't match '$answer'\n";
}
} while (!$matched);
} # TRY:
print "Give value (category):\n";
my $val = $term->readline('INPUT> ');
if ($val) {
$term->addhistory($val);
print "+ $matched: $rule => '$val'\n";
return { $matched => $rule, 'category' => $val };
}
print "\n. skipping all\n";
return;
}
# Update histogram of responses with categorization of
# 'other, please specify' answers
sub update_other_hist {
my ($orepl, $qinfo, $response, @categories) = @_;
return unless @categories;
if (!exists $orepl->{'histogram'}) {
$orepl->{'histogram'} = {};
}
my @answers =
map { $qinfo->{'codes'}[$_-1] }
grep { defined && /^\d+$/ }
(ref($response->{'contents'}) ?
@{$response->{'contents'}} : $response->{'contents'});
# rules:
# - if category matches answer (for multiple-choice)
# it is an explanation, and do not add to histogram
# - if category matches pre-defined answer, but answer was not
# selected, it is correction, and should be added to histogram
# - if category is new, it should be added to histogram
my $has_explanation = 0;
foreach my $category (uniq @categories) {
if (grep { $_ eq $category } @answers) {
$has_explanation = 1;
} else {
add_to_hist($orepl->{'histogram'}, $category);
}
}
add_to_hist($orepl->{'histogram'}, 'EXPLANATION')
if $has_explanation;
}
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# ----------------------------------------------------------------------
# Create histogram
# add_to_hist(HASHREF, LIST)
sub add_to_hist {
my ($hist, @values) = @_;
foreach my $val (@values) {
if (exists $hist->{$val}) {
$hist->{$val}++;
} else {
$hist->{$val} = 1;
}
}
}
# ----------------------------------------------------------------------
# Normalize input data
sub normalize_country {
my $country = shift;
# strip leading and trailing whitespace
$country =~ s/^\s+//;
$country =~ s/\s+$//;
# strip quotes
$country =~ s/^'(.*)'$/$1/;
my $original = $country;
# strip prefix
$country =~ s/^The //i;
# strip extra info
$country =~ s/, Europe\b//i;
$country =~ s/ \(Central Europe\)//;
$country =~ s/, but .*$//i;
$country =~ s/, UK\b//i;
$country =~ s/, the\b//i;
$country =~ s/ \. shanghai\b//i;
$country =~ s/^Kharkiv, //i;
$country =~ s/^Flanders, //i;
$country =~ s/^Tokyo, //i;
$country =~ s/^Victoria, //i;
$country =~ s/ \(Holland\)//i;
$country =~ s/ R\.O\.C\.//i;
$country =~ s/^\.([a-z][a-z])$/$1/i;
$country =~ s/[!?]+$//;
$country =~ s/\bMotherfucking\b //i;
$country =~ s/, bitch\.//;
$country =~ s/ \(fuck yea\)//;
$country =~ s/^China[, ]PRC?$/China/i;
$country =~ s/^(?:P\.R\.|PRC? )China$/China/i;
$country =~ s/^Hong Kong.*/Hong Kong/i;
$country =~ s/^.* - Brazil$/Brazil/i;
$country =~ s/^just south of //i;
# correct (or normalize) spelling
$country =~ s/\brep\.(?:\b|$)/Republic/i;
$country =~ s/\b(?:Amerrica|Ameircia)\b/America/i;
$country =~ s/\bBrasil\b/Brazil/i;
$country =~ s/\bBrazul\b/Brazil/i;
$country =~ s/\bChezh Republic\b/Czech Republic/i;
$country =~ s/\bCzechia\b/Czech Republic/i;
$country =~ s/^Czech$/Czech Republic/i;
$country =~ s/\bChinese\b/China/i;
$country =~ s/\bChinease\b/China/i;
$country =~ s/\bEnglang\b/England/i;
$country =~ s/\bEngkand\b/England/i;
$country =~ s/\bFinnland\b/Finland/i;
$country =~ s/\bFrench\b/France/i;
$country =~ s/\bFederal Republic of Germany\b/Germany/i;
$country =~ s/\bGerman[u]?\b/Germany/i;
$country =~ s/\bGernany\b/Germany/i;
$country =~ s/\bKyrgyzstab\b/Kyrgyzstan/i;
$country =~ s/\bLithuani\b/Lithuania/i;
$country =~ s/\bMacedoni\b/Macedonia/i;
$country =~ s/\bM.*xico\b/Mexico/i;
$country =~ s/\bMolodva\b/Moldova/i;
$country =~ s/\bSapin\b/Spain/i;
#$country =~ s/^Serbia$/Serbia and Montenegro/i; # outdated info
#$country =~ s/^Montenegro$/Serbia and Montenegro/i; # outdated info (?)
$country =~ s/\b(?:Swiss|Sitzerland|Swtzerland)\b/Switzerland/i;
$country =~ s/\bSwedeb\b/Sweden/i;
$country =~ s/\bUnited Kindom\b/United Kingdom/i;
$country =~ s/\bViet Nam\b/Vietnam/i;
$country =~ s/\bZealandd\b/Zealand/i;
$country =~ s/\bUSUnited States\b/United States/i;
$country =~ s/\bUni?ted? States?\b/United States/i;
# many names of United States of America
$country =~ s/^U\.S(?:|\.|\.A|\.A\.)$/USA/;
$country =~ s/^U\. S\. A\.$/USA/;
$country =~ s/^US of A$/USA/;
$country =~ s/^USofA$/USA/;
$country =~ s/^US&A$/USA/;
$country =~ s/^YS$/USA/;
# many names of United Kingdom
$country =~ s/^Britain$/United Kingdom/i;
$country =~ s/^British$/United Kingdom/i;
# local name to English
$country =~ s/\bDeutschland\b/Germany/i;
# other fixes and expansions
$country =~ s/^PRC$/China/i; # People's Republic of China
$country =~ s/^U[Kk]$/United Kingdom/;
$country =~ s/\bUK\b/United Kingdom/i;
$country =~ s/ \(Rep\. of\)/, Republic of/;
$country =~ s/\b(?:Unites|Unitered)\b/United/i;
$country =~ s/\bStatus\b/States/i;
$country =~ s/\bState2\b/States/i;
$country =~ s/^Russian$/Russian Federation/i;
$country =~ s/^America$/USA/i;
# fix accidental fuzzy matches
$country =~ s/^Mike$/unknown/i;
# province, state or city to country
$country =~ s/^.*(?:England|Scotland|Wales).*$/United Kingdom/i;
$country =~ s/^Northern Ireland$/United Kingdom/i;
$country =~ s/\bTexas\b/USA/i;
$country =~ s/\bCalgary\b/Canada/i;
$country =~ s/\bAdelaide\b/Australia/i;
$country =~ s/\bAmsterdam\b/Netherlands/i;
$country =~ s/\bBasque country\b/Spain/i;
$country =~ s/\bBeijing\b/China/i;
$country =~ s/\bBerlin\b/Germany/i;
$country =~ s/\bCatalonia\b/Spain/i;
$country =~ s/^Catalunya \/ Spain$/Spain/i;
$country =~ s/\bOttawa\b/Canada/i;
$country =~ s/\bReunion Island\b/France/i;
# choose only one country if there are more than one provided
$country =~ s/ <-> .*$//;
#$country =~ s/ and .*$//; # false positives in country names
$country =~ s!/.*$!!;
$country =~ s!, .*$!!;
# convert to code and back to country, normalizing country name
# (or going from code to country)
if ($country) {
my $code = country2code($country) || $country;
$country = code2country($code) || $country;
}
unless (scalar grep { $_ eq $country } @country_names) {
# 2/3 of Schwartzian transform
my @countries_sorted =
sort { $a->[1] <=> $b->[1] }
map { [$_, distance($_, $country)] }
@country_names;
if ($countries_sorted[0][1] <= 2) {
$country = $countries_sorted[0][0];
} else {
#$country .= " ($countries_sorted[0][0],$countries_sorted[0][1])";
$country .= '?';
if ($original ne $country) {
$country .= " [$original]";
}
}