PageRenderTime 63ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/Lingua-Identify-Blacklists/lib/Lingua/Identify/Blacklists.pm

https://bitbucket.org/tiedemann/blacklist-classifier
Perl | 811 lines | 577 code | 187 blank | 47 comment | 74 complexity | 2d19d0ecb01d177310310aacded8a41e MD5 | raw file
  1. #-*-perl-*-
  2. package Lingua::Identify::Blacklists;
  3. use 5.008;
  4. use strict;
  5. use File::ShareDir qw/dist_dir/;
  6. use File::Basename qw/dirname/;
  7. use File::GetLineMaxLength;
  8. use Lingua::Identify qw(:language_identification);;
  9. use Lingua::Identify::CLD;
  10. use Exporter 'import';
  11. our @EXPORT_OK = qw( identify identify_file identify_stdin
  12. train train_blacklist run_experiment
  13. available_languages available_blacklists );
  14. our %EXPORT_TAGS = ( all => \@EXPORT_OK );
  15. our $VERSION = '0.04b';
  16. =encoding UTF-8
  17. =head1 NAME
  18. Lingua::Identify::Blacklists - Language identification for related languages based on blacklists
  19. =head1 SYNOPSIS
  20. use Lingua::Identify::Blacklists qw/:all/;
  21. # detect language for a given text
  22. # (discriminate between Bosanian, Croatian and Serbian)
  23. my $lang = identify( ".... text to be classified ...",
  24. langs => ['bs','hr','sr']);
  25. # check if the assumed language ('hr') is confused with another one
  26. my $lang = identify( ".... text to be classified ...", assumed => 'hr' );
  27. # use a general-purpose identfier and check confusable langauges if necessary
  28. my $lang = identify( ".... text to be classified ...");
  29. # delect language in the given file (Unicode UTF-8 is assumed)
  30. my $lang = identify_file( $filename, langs => [...] );
  31. my $lang = identify_file( $filename, assumed => '..' );
  32. my $lang = identify_file( $filename );
  33. # delect language for every line separately from the given file
  34. # (return a list of lang-IDs)
  35. my @langs = identify_file( $filename, every_line => 1, langs = [...] );
  36. my @langs = identify_file( $filename, every_line => 1, assumed = '..' );
  37. my @langs = identify_file( $filename, every_line => 1 );
  38. # learn classifiers (blacklists) for all pairs of languages
  39. # given some training data
  40. train( { cs => $file_with_cs_text,
  41. sk => $file_with_sk_text,
  42. pl => $file_with_pl_text } );
  43. # learn a blacklist from a given pair of texts (prints to STDOUT)
  44. train_blacklist( $filename1, $filename2 );
  45. # ... the same but write to outfile
  46. train_blacklist( $filename1, $filename2, outfile => $outfilename );
  47. # train and evaluate the classification using given training/test data
  48. my @traindata = ($trainfile1, $trainfile2, $trainfile3);
  49. my @evaldata = ($testfile1, $testfile2, $testfile3);
  50. run_experiment(\@traindata, \@evaldata, $lang1 $lang2, $lang3);
  51. # train with different parameters (optional)
  52. my %para = (
  53. min_high => 5, # minimal token frequency in one langusgae
  54. max_low => 2, # maximal token frequency in the other language
  55. min_diff => 0.7 ); # score difference threshold
  56. train( { cs => $file_with_cs_text, sk => $file_with_sk_text }, %para );
  57. =head1 Description
  58. This module adds a blacklist classifier to a general purpose language identification tool. Related languages can easily be confused with each other and standard language detection tools do not work very well for distinguishing them. With this module one can train so-called blacklists of words for language pairs containing words that should not (or very rarely) occur in one language while being quite common in the other. These blacklists are then used to discriminate between those "confusable" related languages.
  59. Since version 0.03 it also integrates a standard language identifier (Lingua::Identify::CLD) and can now be used for general language identification. It calls the blacklist classifier only for those languages that can be confused and for which appropriate blacklists are trained.
  60. =head1 Settings
  61. Module-internal variables that can be modified:
  62. $BLACKLISTDIR # directory with all blacklists (default: module-share-dir)
  63. $LOWERCASE # lowercase all data, yes/no (1/0), default: 1
  64. $TOKENIZE # tokenize all data, yes/no (1/0), default: 1
  65. $ALPHA_ONLY # don't use tokens with non-alphabetic characters, default: 1
  66. $MAX_LINE_LENGTH # max line length when reading from files (default=2**16)
  67. $CLD_TEXT_SIZE # text size in characters used for language ident. with CLD
  68. $VERBOSE # verbose output (default=0)
  69. Tokenization is very simple and replaces all non-alphabetic characters with a white-space character.
  70. =cut
  71. our $BLACKLISTDIR;
  72. eval{ $BLACKLISTDIR = &dist_dir('Lingua-Identify-Blacklists') . '/blacklists' };
  73. our $LOWERCASE = 1;
  74. our $TOKENIZE = 1;
  75. our $ALPHA_ONLY = 1;
  76. our $MAX_LINE_LENGTH = 2**16; # limit the length of one line to be read
  77. our $CLD_TEXT_SIZE = 2**16; # text size used for detecting lang with CLD
  78. our $VERBOSE = 0;
  79. my %blacklists = (); # hash of blacklists (langpair => {blacklist}, ...)
  80. my %confusable = (); # hash of confusable languages (lang => [other_langs])
  81. ## the compact language identifier from Google Chrome
  82. my $CLD = new Lingua::Identify::CLD;
  83. # load all blacklists in the gneral BLACKLISTDIR
  84. &load_blacklists( $BLACKLISTDIR );
  85. =head1 Exported Functions
  86. =head2 C<$langID = identify( $text [,%options] )>
  87. Analyses a given text and returns a language ID as the result of the classification. C<%options> can be used to change the behaviour of the classifier. Possible options are
  88. assumed => $assumed_lang
  89. langs => \@list_of_possible_langs
  90. use_margin => $score
  91. If C<langs> are specified, it runs the classifier with blacklists for those languages (in a cascaded way, i.e. best1 = lang1 vs lang2, best2 = best1 vs lang3, ...). If C<use_margin> is specified, it runs all versus all and returns the language that wins the most (with margin=$score).
  92. If the C<assumed> language is given, it runs the blacklist classifier for all languages that can be confused with $assumed_lang (if blacklist models exist for them).
  93. If neither C<langs> not C<assumed> are specified, it first runs a general-purpose language identification (using Lingua::Identify::CLD and Lingua::Identify) and then checks with the blacklist classifier whether the detected language can be confused with another one. For example, CLD frequently classifies Serbian and Bosnian texts as Croatian but the blacklist classifier will detect that (and hopefully correct the decision).
  94. =cut
  95. sub identify{
  96. my $text = shift;
  97. my %options = @_;
  98. my %dic = ();
  99. my $total = 0;
  100. # run the blacklist classifier if 'langs' are specified
  101. if (exists $options{langs}){
  102. &process_string( $text, \%dic, $total, $options{text_size} );
  103. return &classify( \%dic, %options );
  104. }
  105. # otherwise: check if there is an 'assumed' language
  106. # if not: classify with CLD
  107. $options{assumed} = &identify_language( $text )
  108. unless (exists $options{assumed});
  109. # if there is an 'assumed' language:
  110. # check if it can be confused with others (i.e. blacklists exist)
  111. if (exists $confusable{$options{assumed}}){
  112. $options{langs} = $confusable{$options{assumed}};
  113. # finally: process the text and classify
  114. &process_string( $text, \%dic, $total );
  115. return &classify( \%dic, %options );
  116. }
  117. return $options{assumed};
  118. }
  119. =head2 C<$langID = identify_file( $filename [,%options] )>
  120. Does the same as C<identify> but reads text from a file. It also takes the same options as the 'identify' function but allows two extra options:
  121. text_size => $size, # number of tokens to be used for classification
  122. every_line => 1
  123. Using the C<every_line> option, the classifier checks every input line seperately and returns a list of language ID's.
  124. @langIDs = identify_file( $filename, every_line => 1, %options )
  125. =cut
  126. sub identify_file{
  127. my $file = shift;
  128. my %options = @_;
  129. my %dic = ();
  130. my $total = 0;
  131. my @predictions = ();
  132. my $fh = defined $file ? open_file($file) : *STDIN;
  133. my $reader = File::GetLineMaxLength->new($fh);
  134. # mode 1: classify every line separately
  135. if ($options{every_line}){
  136. my @predictions = ();
  137. while (my $line = $reader->getline($MAX_LINE_LENGTH)) {
  138. chomp $line;
  139. push( @predictions, &identify( $line, %options ) );
  140. }
  141. return @predictions;
  142. }
  143. # mode 2: classify all text together (optional: size limit)
  144. my $text = '';
  145. while (my $line = $reader->getline($MAX_LINE_LENGTH)) {
  146. # save text if no languages are given (for blacklists)
  147. unless (exists $options{langs} || exists $options{assumed}){
  148. if ( length($text) < $CLD_TEXT_SIZE ){
  149. $text .= $line;
  150. }
  151. }
  152. # prepare the data for blacklist classification
  153. # (TODO: is this cheaper than keeping the text in memory and
  154. # processing it later when needed?)
  155. chomp $line;
  156. &process_string($line,\%dic,$total);
  157. if ($options{text_size}){ # use only a certain number of words
  158. if ($total > $options{text_size}){
  159. print STDERR "use $total tokens for classification\n"
  160. if ($VERBOSE);
  161. last;
  162. }
  163. }
  164. }
  165. # no languages selected?
  166. unless (exists $options{langs}){
  167. # no assumed language set
  168. unless (exists $options{assumed}){
  169. # try to identify with the text we have saved above
  170. $options{assumed} = &identify_language( $text )
  171. unless (exists $options{assumed});
  172. }
  173. if (exists $confusable{$options{assumed}}){
  174. $options{langs} = $confusable{$options{assumed}};
  175. }
  176. }
  177. # finally: classify with blacklists
  178. if (exists $options{langs}){
  179. return &classify( \%dic, %options );
  180. }
  181. # no blacklists in this case ...
  182. return $options{assumed};
  183. }
  184. =head2 C<$langID = identify_stdin( [,%options] )>
  185. The same as C<identify_file> but reads from STDIN
  186. =cut
  187. sub identify_stdin{
  188. return identify_file( undef, @_ );
  189. }
  190. =head2 C<train( \%traindata [,%options] )>
  191. Trains classifiers by learning blacklisted words for pairwise language discrimination. Returns nothing. Blacklists are stored in C<Lingua::Identify::Blacklists::BLACKLISTDIR/>. You may have to run the process as administrator if you don't have write permissions.
  192. C<%traindata> is a hash of training data files associated with their corresponding language IDs:
  193. 'hr' => $croatian_text_file,
  194. 'sr' => $serbian_text_file,
  195. ...
  196. C<%options> is a hash of optional parameters that change the behaviour of the learning algorithm. Possible parameters are:
  197. min_high => $freq1, # minimal token frequency in one langusgae
  198. max_low => $freq2, # maximal token frequency in the other language
  199. min_diff => $score, # score difference threshold
  200. text_size => $size, # maximum number of tokens to be used per text
  201. =cut
  202. sub train{
  203. my $traindata = shift;
  204. my %options = @_;
  205. my @langs = keys %{$traindata};
  206. for my $s (0..$#langs){
  207. for my $t ($s+1..$#langs){
  208. print "traing blacklist for $langs[$s]-$langs[$t] ... ";
  209. &train_blacklist( $$traindata{$langs[$s]},$$traindata{$langs[$t]},
  210. outfile => "$BLACKLISTDIR/$langs[$s]-$langs[$t].txt",
  211. %options );
  212. print "saved in '$BLACKLISTDIR/$langs[$s]-$langs[$t].txt'\n";
  213. }
  214. }
  215. }
  216. =head2 C<train_blacklist( $file1, $file2, %options )>
  217. This function learns a blacklist of words to discriminate between the language given in $file1 and the language given in $file2. It takes the same arguments (%options) as the C<train> function above with one additional parameter:
  218. outfile => $output_file
  219. Using this parameter, the blacklist will be written to the specified file. Otherwise it will be printed to STDOUT.
  220. The function returns nothing otherwise.
  221. =cut
  222. sub train_blacklist{
  223. my ($file1,$file2,%options) = @_;
  224. my $min_high = exists $options{min_high} ? $options{min_high} : 10;
  225. my $max_low = exists $options{min_low} ? $options{max_low} : 3;
  226. my $min_diff = exists $options{min_diff} ? $options{min_diff} : 0.8;
  227. my %dic1=();
  228. my %dic2=();
  229. my $total1 = &read_file($file1,\%dic1,$options{text_size});
  230. my $total2 = &read_file($file2,\%dic2,$options{text_size});
  231. if ($options{outfile}){
  232. mkdir dirname($options{outfile}) unless (-d dirname($options{outfile}));
  233. open O,">$options{outfile}" || die "cannot write to $options{outfile}\n";
  234. binmode(O,":encoding(UTF-8)");
  235. }
  236. foreach my $w (keys %dic1){
  237. next if ((!exists $dic1{$w} || $dic1{$w}<$min_high) &&
  238. (!exists $dic2{$w} || $dic2{$w}<$min_high));
  239. next if ((exists $dic1{$w} && $dic1{$w}>$max_low) &&
  240. (exists $dic2{$w} && $dic2{$w}>$max_low));
  241. my $c1 = exists $dic1{$w} ? $dic1{$w} : 0;
  242. my $c2 = exists $dic2{$w} ? $dic2{$w} : 0;
  243. my $s1 = $c1 * $total2;
  244. my $s2 = $c2 * $total1;
  245. my $diff = ($s1 - $s2) / ($s1 + $s2);
  246. if (abs($diff) > $min_diff){
  247. if ($options{outfile}){
  248. print O "$diff\t$w\t$c1\t$c2\n";
  249. }
  250. else{
  251. print "$diff\t$w\t$c1\t$c2\n";
  252. }
  253. }
  254. }
  255. # don't forget words that do NOT appear in dic1!!!
  256. foreach my $w (keys %dic2){
  257. next if (exists $dic1{$w});
  258. next if ($dic2{$w}<10);
  259. my $c1 = exists $dic1{$w} ? $dic1{$w} : 0;
  260. my $c2 = exists $dic2{$w} ? $dic2{$w} : 0;
  261. if ($options{outfile}){
  262. print O "-1\t$w\t$c1\t$c2\n";
  263. }
  264. else{
  265. print "-1\t$w\t$c1\t$c2\n";
  266. }
  267. }
  268. close O if ($options{outfile});
  269. }
  270. =head2 C<@langs = available_languages()>
  271. Returns a list of languages covered by the blacklists in the BLACKLISTDIR.
  272. =cut
  273. sub available_languages{
  274. unless (keys %blacklists){
  275. &load_blacklists( $BLACKLISTDIR );
  276. }
  277. my %langs = ();
  278. foreach (keys %blacklists){
  279. my ($lang1,$lang2) = split(/\-/);
  280. $langs{$lang1}=1;
  281. $langs{$lang2}=1;
  282. }
  283. return keys %langs;
  284. }
  285. =head2 C<%lists = available_blacklists()>
  286. Resturns a hash of available language pairs (for which blacklists exist in the system).
  287. %lists = ( srclang1 => { trglang1a => blacklist1a, trglang1b => blacklist1b },
  288. srclang2 => { trglang2a => blacklist2a, ... }
  289. .... )
  290. =cut
  291. sub available_blacklists{
  292. unless (keys %blacklists){
  293. &load_blacklists( $BLACKLISTDIR );
  294. }
  295. my %pairs = ();
  296. foreach (keys %blacklists){
  297. my ($lang1,$lang2) = split(/\-/);
  298. $pairs{$lang1}{$lang2} = $_;
  299. $pairs{$lang2}{$lang1} = $_
  300. unless (defined $pairs{$lang2} && defined $pairs{$lang2}{$lang1});
  301. }
  302. return %pairs;
  303. }
  304. =head2 C<run_experiment( \@trainfiles, \@testfiles, \%options, @langs )>
  305. This function allows to run experiments, i.e. training and evaluating classifiers for the given languages (C<@langs>). The arrays of training data and test data need to be of the same size as C<@langs>. The function prints the overall accurcy and a confusion table given the data sets and the classification. C<%options> can be used to set classifier-specific parameters.
  306. =cut
  307. sub run_experiment{
  308. use Benchmark;
  309. my $trainfiles = shift;
  310. my $evalfiles = shift;
  311. my $options = ref($_[0]) eq 'HASH' ? shift : {};
  312. my @traindata =
  313. ref($trainfiles) eq 'ARRAY' ? @{$trainfiles} : split(/\s+/,$trainfiles);
  314. my @evaldata =
  315. ref($evalfiles) eq 'ARRAY' ? @{$evalfiles} : split(/\s+/,$evalfiles);
  316. my @langs = @_;
  317. die "no languages given!\n" unless (@langs);
  318. die "no training nor evaluation data given!\n"
  319. unless ($#traindata == $#evaldata || $#traindata == $#langs || $#evaldata == $#langs);
  320. $BLACKLISTDIR = $$options{blacklist_dir} || "blacklist-experiment";
  321. # train blacklists
  322. if ($#traindata == $#langs){
  323. my $t1 = new Benchmark;
  324. my %trainset = ();
  325. for (0..$#langs){ $trainset{$langs[$_]} = $traindata[$_]; }
  326. &train( \%trainset, %{$options} );
  327. print STDERR "training took: ".
  328. timestr(timediff(new Benchmark, $t1)).".\n";
  329. }
  330. &initialize();
  331. # classify test data
  332. if ($#evaldata == $#langs){
  333. print STDERR "classify ....\n";
  334. my $correct=0;
  335. my $count=0;
  336. my %guesses=();
  337. my %correct_lang=();
  338. my %count_lang=();
  339. my $t1 = new Benchmark;
  340. foreach my $i (0..$#langs){
  341. open IN,"<:encoding(UTF-8)",$evaldata[$i] || die "...";
  342. while (<IN>){
  343. chomp;
  344. my %dic = ();
  345. &process_string($_,\%dic);
  346. my $guess = &classify(\%dic,@langs);
  347. $count++;
  348. $count_lang{$langs[$i]}++;
  349. if ($guess eq $langs[$i]){
  350. $correct++;
  351. $correct_lang{$langs[$i]}++;
  352. }
  353. $guesses{$langs[$i]}{$guess}++;
  354. }
  355. close IN;
  356. }
  357. print STDERR "classification took: ".
  358. timestr(timediff(new Benchmark, $t1)).".\n";
  359. printf "accuracy: %6.4f\n ",$correct/$count;
  360. foreach my $c (@langs){
  361. print " $c";
  362. }
  363. print "\n";
  364. foreach my $c (@langs){
  365. print "$c ";
  366. foreach my $g (@langs){
  367. printf "%4d",$guesses{$c}{$g};
  368. }
  369. printf " %6.4f",$correct_lang{$c}/$count_lang{$c};
  370. print "\n";
  371. }
  372. }
  373. system("wc -l $Lingua::Identify::Blacklists::BLACKLISTDIR/*.txt");
  374. }
  375. =head2 Module-internal functions
  376. The following functions are not exported and are mainly used for internal purposes (but may be used from the outside if needed).
  377. initialize() # reset the repository of blacklists
  378. identify_language($text) # return lang-ID for $text (using CLD)
  379. classify(\%dic,%options) # run the classifier
  380. classify_cascaded(\%dic,@langs) # run a cascade of binary classifications
  381. # run all versus all and return the one that wins most binary decisions
  382. # (a score margin is used to adjust the reliability of the decisions)
  383. classify_with_margin(\%dic,$margin,@langs)
  384. load_blacklists($dir) # load all blacklists available in $dir
  385. load_blacklist(\%list,$dir, # load a lang-pair specific blacklist
  386. $lang1,$lang2)
  387. read_file($file,\%dic,$max) # read a file and count token frequencies
  388. process_string($string) # process a given string (lowercasing ...)
  389. =cut
  390. sub initialize{ %blacklists = (); %confusable = (); }
  391. sub identify_language{
  392. my ($lang, $id, $conf) = $CLD->identify( $_[0] );
  393. # strangely enough CLD is not really reliable for English
  394. # (all kinds of garbish input is recognized as English)
  395. # --> check with Lingua::Identify
  396. if ($id eq 'en'){
  397. $id = $id = langof( $_[0] ) ? $id : 'unknown';
  398. }
  399. return $id;
  400. }
  401. sub classify{
  402. my $dic = shift;
  403. my %options = @_;
  404. $options{langs} = '' unless ($options{langs});
  405. my @langs = ref($options{langs}) eq 'ARRAY' ?
  406. @{$options{langs}} : split( /\s+/, $options{langs} ) ;
  407. @langs = available_languages() unless (@langs);
  408. return &classify_with_margin( $dic, $options{use_margin}, @langs )
  409. if ($options{use_margin});
  410. return &classify_cascaded( $dic, @langs );
  411. }
  412. sub classify_cascaded{
  413. my $dic = shift;
  414. my @langs = @_;
  415. my $lang1 = shift(@langs);
  416. foreach my $lang2 (@langs){
  417. # load blacklists on demand
  418. unless (exists $blacklists{"$lang1-$lang2"}){
  419. $blacklists{"$lang1-$lang2"}={};
  420. &load_blacklist($blacklists{"$lang1-$lang2"},
  421. $BLACKLISTDIR,$lang1,$lang2);
  422. }
  423. my $list = $blacklists{"$lang1-$lang2"};
  424. my $score = 0;
  425. foreach my $w (keys %{$dic}){
  426. if (exists $$list{$w}){
  427. $score += $$dic{$w} * $$list{$w};
  428. print STDERR "$$dic{$w} x $w found ($$list{$w})\n" if ($VERBOSE);
  429. }
  430. }
  431. if ($score < 0){
  432. $lang1 = $lang2;
  433. }
  434. print STDERR "select $lang1 ($score)\n" if ($VERBOSE);
  435. }
  436. return $lang1;
  437. }
  438. # OTHER WAY OF CLASSIFYING
  439. # test all against all ...
  440. sub classify_with_margin{
  441. my $dic = shift;
  442. my $margin = shift;
  443. my @langs = @_;
  444. my %selected = ();
  445. while (@langs){
  446. my $lang1 = shift(@langs);
  447. foreach my $lang2 (@langs){
  448. # load blacklists on demand
  449. unless (exists $blacklists{"$lang1-$lang2"}){
  450. $blacklists{"$lang1-$lang2"}={};
  451. &load_blacklist($blacklists{"$lang1-$lang2"},
  452. $BLACKLISTDIR,$lang1,$lang2);
  453. }
  454. my $list = $blacklists{"$lang1-$lang2"};
  455. my $score = 0;
  456. foreach my $w (keys %{$dic}){
  457. if (exists $$list{$w}){
  458. $score += $$dic{$w} * $$list{$w};
  459. print STDERR "$$dic{$w} x $w found ($$list{$w})\n"
  460. if ($VERBOSE);
  461. }
  462. }
  463. next if (abs($score) < $margin);
  464. if ($score < 0){
  465. # $selected{$lang2}-=$score;
  466. $selected{$lang2}++;
  467. print STDERR "select $lang2 ($score)\n" if ($VERBOSE);
  468. }
  469. else{
  470. # $selected{$lang1}+=$score;
  471. $selected{$lang1}++;
  472. print STDERR "select $lang1 ($score)\n" if ($VERBOSE);
  473. }
  474. }
  475. }
  476. my ($best) = sort { $selected{$b} <=> $selected{$a} } keys %selected;
  477. return $best;
  478. }
  479. # load_all_blacklists = alias for load_blacklists
  480. sub load_all_blacklists{ return load_blacklists(@_); }
  481. sub load_blacklists{
  482. my $dir = shift || $BLACKLISTDIR;
  483. opendir(my $dh, $dir) || die "cannot read directory '$dir'\n";
  484. while(my $d = readdir $dh) {
  485. # print STDERR "found $d in $dir found!\n";
  486. if ($d=~/^(.*)-(.*).txt$/){
  487. $blacklists{"$1-$2"}={};
  488. &load_blacklist($blacklists{"$1-$2"}, $dir, $1, $2);
  489. }
  490. # else{
  491. # print STDERR "unrecognized file $d in $dir found!\n";
  492. # }
  493. }
  494. closedir $dh;
  495. if (keys %blacklists){
  496. # update list of confusable languages
  497. my %lists = &available_blacklists();
  498. foreach my $lang (keys %lists){
  499. @{$confusable{$lang}} = keys %{$lists{$lang}};
  500. unshift( @{$confusable{$lang}}, $lang );
  501. }
  502. }
  503. }
  504. sub load_blacklist{
  505. my ($list,$dir,$lang1,$lang2) = @_;
  506. my $inverse = 0;
  507. if (! -e "$dir/$lang1-$lang2.txt"){
  508. ($lang1,$lang2) = ($lang2,$lang1);
  509. $inverse = 1;
  510. }
  511. open F,"<:encoding(UTF-8)","$dir/$lang1-$lang2.txt" || die "...";
  512. while (<F>){
  513. chomp;
  514. my ($score,$word) = split(/\t/);
  515. $$list{$word} = $inverse ? 0-$score : $score;
  516. }
  517. close F;
  518. }
  519. sub open_file{
  520. my $file = shift;
  521. # allow gzipped input
  522. my $fh;
  523. if ($file=~/\.gz$/){
  524. open $fh,"gzip -cd < $file |" || die "cannot open file '$file'";
  525. binmode($fh,":encoding(UTF-8)");
  526. }
  527. else{
  528. open $fh,"<:encoding(UTF-8)",$file || die "cannot open file '$file'";
  529. }
  530. return $fh;
  531. }
  532. sub read_file{
  533. my ($file,$dic,$max)=@_;
  534. # use File::GetLineMaxLength to avoid filling the memory
  535. # when reading from files without new lines
  536. my $fh = open_file( $file );
  537. my $reader = File::GetLineMaxLength->new($fh);
  538. my $total = 0;
  539. while (my $line = $reader->getline($MAX_LINE_LENGTH)) {
  540. chomp $line;
  541. &process_string($line,$dic,$total);
  542. if ($max){
  543. if ($total > $max){
  544. print STDERR "read $total tokens from $file\n";
  545. last;
  546. }
  547. }
  548. }
  549. close $fh;
  550. return $total;
  551. }
  552. # process_string($string,\%dic,\$wordcount[,$maxwords])
  553. sub process_string{
  554. $_[0]=lc($_[0]) if ($LOWERCASE);
  555. $_[0]=~s/((\A|\s)\P{IsAlpha}+|\P{IsAlpha}+(\s|\Z))/ /gs if ($TOKENIZE);
  556. my @words = $ALPHA_ONLY ?
  557. grep(/^\p{IsAlpha}/,split(/\s+/,$_[0])) :
  558. split(/\s+/,$_[0]);
  559. # use only $maxwords words
  560. splice(@words,$_[3]) if ($_[3]);
  561. foreach my $w (@words){${$_[1]}{$w}++;$_[2]++;}
  562. }
  563. 1;
  564. __END__
  565. =head1 AUTHOR
  566. Jörg Tiedemann, L<https://bitbucket.org/tiedemann>
  567. =head1 BUGS
  568. Please report any bugs or feature requests to
  569. L<https://bitbucket.org/tiedemann/blacklist-classifier>.
  570. =head1 SUPPORT
  571. You can find documentation for this module with the perldoc command.
  572. perldoc Lingua::Identify::Blacklists
  573. =head1 SEE ALSO
  574. This module is designed for the discrimination between closely related languages. For general-purpose language identification look at L<Lingua::Identify>, L<Lingua::Identify::CLD> and L<Lingua::Ident>
  575. =head1 LICENSE AND COPYRIGHT
  576. Copyright 2012 Jörg Tiedemann.
  577. This program is free software: you can redistribute it and/or modify
  578. it under the terms of the GNU Lesser General Public License as published
  579. by the Free Software Foundation, either version 3 of the License, or
  580. (at your option) any later version.
  581. This program is distributed in the hope that it will be useful,
  582. but WITHOUT ANY WARRANTY; without even the implied warranty of
  583. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  584. GNU Lesser General Public License for more details.
  585. You should have received a copy of the GNU Lesser General Public License
  586. along with this program. If not, see L<http://www.gnu.org/licenses/>.
  587. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  588. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  589. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  590. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  591. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  592. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  593. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  594. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  595. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  596. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  597. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  598. =cut