Created
December 14, 2016 15:54
-
-
Save takdavid/3fa2cc3ae21aa96da24b8bd90b8c63b0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use Unicode::UCD 'charinfo'; | |
use Unicode::Normalize 'isNonStDecomp', 'NFD', 'NFC', 'isComp2nd', 'isNonStDecomp'; | |
use charnames ':full'; | |
use Encode; | |
use HTML::Entities; | |
#use Getopt::Std; | |
#our ($opt_f, $opt_r); | |
#getopts('fr'); | |
binmode(STDOUT, ':utf8'); | |
sub usage | |
{ | |
print <<eof | |
Usage: | |
./unicount.pl <infile >outfile | |
Ordered by counts: | |
./unicount.pl <infile | sort -r -n >outfile | |
eof | |
} | |
my %count; | |
my $composition; | |
my $line; | |
my @charcodes; | |
while ($line = <>) | |
{ | |
$line = Encode::decode("UTF-8", $line); | |
$line = decode_entities($line); | |
$line = NFD($line); | |
@charcodes = unpack("U0U*", $line); | |
for ($i=0; $i<=$#charcodes; $i++) | |
{ | |
$charcode = $charcodes[$i]; | |
$chr = substr $line, $i, 1; | |
# combining characters together with the starter | |
if (isComp2nd($charcode) || isNonStDecomp($charcode)) | |
{ | |
$composition .= $chr; | |
} | |
else | |
{ | |
$count{$composition}++; | |
$composition = $chr; | |
} | |
} | |
$count{$composition}++; | |
} | |
delete $count{''}; | |
while (($composition, $cnt) = each(%count)) | |
{ | |
@charcodes = (); | |
@charnames = (); | |
foreach $chr (split(//, $composition)) | |
{ | |
$charcode = unpack("U0U*", $chr); | |
push @charcodes, sprintf('%04X', $charcode); | |
push @charnames, charnames::viacode($charcode); | |
} | |
$composition = '' if ($composition =~ /[\r\t\n]/); | |
printf "%d\t%s\t%s\t%s\n", $cnt, $composition, join(' + ', @charcodes), join(' + ', @charnames); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This script counts letters in its starndard input, where letter means a unicode code point base character together with its combining characters (diacritics etc.). Characters are first decomposed by canonical equivalence (NFD), so that combining characters are arranged in a specific order, so similarly looking letters that are differently encoded will be taken as equals.
The input is expected to be in utf-8, the output is also utf-8, unsorted, and tab separated; the columns are: counter; normalized combined character; hex code of the character(s) joined by
+
; standard name of the character(s) joined by+
.For example, the command:
would output: