确定亚洲/日语字符终端的宽度?

问题描述 投票:0回答:1

在我的终端中,它们同样宽:

ヌー平行
parallel
æøåüäöûß

same width of same width of

我已经设法让 Perl 给出最后 2 行的长度 8,但它报告第一行的长度为 4。有没有办法让我确定ヌ的宽度是 ø 的两倍?

perl cjk kanji katakana
1个回答
4
投票

您可以使用Text::CharWidth

mbswidth
。它使用 POSIX 的
wcwidth

use v5.14;
use warnings;

use utf8;
use open ':std', ':encoding(UTF-8)';

use Encode             qw( encode_utf8 );
use Text::CharWidth    qw( mbswidth );
use Unicode::Normalize qw( NFC NFD );

my @tests = (
   [ "ASCII",     "parallel",      8 ],
   [ "NFC",       NFC("æøåüäöûß"), 8 ],
   [ "NFD",       NFD("æøåüäöûß"), 8 ],
   [ "EastAsian", "ヌー平行",      8 ],
);

for ( @tests ) {
   my ( $name, $s, $expect ) = @$_;
   my $length = length( $s );
   my $got = mbswidth( encode_utf8( $s ) );
   printf "%-9s length=%2d expect=%d got=%d\n", 
      $name, $length, $expect, $got;
}
ASCII     length= 8 expect=8 got=8
NFC       length= 8 expect=8 got=8
NFD       length=13 expect=8 got=8
EastAsian length= 4 expect=8 got=8

请注意,

mbswidth
需要使用语言环境的编码进行编码的字符串,我假设上述程序中的两个位置是 UTF-8。


如果您想知道字符串根据 Unicode 应采用的列数,请参阅 Unicode 标准附件 #11。请注意,答案可能取决于一个人是否处于东亚环境中。例如,U+03A6 希腊大写字母 PHI(“Φ”)在东亚语境中占用两列,而在其他情况下仅占用一列。

© www.soinside.com 2019 - 2024. All rights reserved.