作者liyih ()
看板Perl
标题Re: [问题] does not map to big5-eten
时间Tue Mar 22 13:36:37 2011
以下分享一下处理 charset encoding 的经验:
如果来源的资料有确定的 charset,那麽您可以考虑
将它转为 Perl's string (不需考虑 Perl 内部实际的编码方式),
再交给模组去处理,最後再依据目的 charset 输出资料。
如:
1. big5 (bytes) => Perl's string (chars) => utf-8 (bytes)
2. utf-8 (bytes) => Perl's string (chars) => big5 (bytes)
3. big5 mix utf-8 (bytes) => Perl's string (chars) => utf-8 (bytes)
对於来源资料的 charset 如果没有明确指定,或是如
big5 mix utf-8 这种存在多种 charset 混在一起的,
可以使用 Encode::Guess 来处理。这常见於抓取网页
内容,但未告知明确的 charset,或是内容与宣告的
charset 不一致。
以下是针对网页内容存在 big5 mix utf-8 都转成 utf-8:
use Encode::Guess qw(big5-eten);
sub convert_to_utf8 {
my ($data) = @_;
my $result = '';
my $p_str = '';
my $utf8 = '';
for ( split( /\r?\n/, $data ) ) {
my $enc = guess_encoding($_);
if ( ref($enc) ) { # convert
$p_str = decode( $enc->name, $_ ); # perl-string
$utf8 = encode( 'utf8', $p_str ); # utf8
}
else { # no conversion
$utf8 = $_;
}
$result .= "$utf8\n";
}
return $result;
}
另外,再分享一个将 utf-8 转成 big5 的作法,
转不过去的就改用 html entities 表示:
use HTML::Entities;
sub utf8_to_big5 {
my ( $str, $is_safe ) = @_;
$is_safe = defined($is_safe) ? $is_safe : 1;
my $result = '';
if ($is_safe) {
my $ucs = decode( "utf-8", $str );
foreach ( split( //, $ucs ) ) {
my $c = encode( "big-5", $_, Encode::FB_QUIET );
$c = encode_entities($_) if ( $c eq '' );
$result .= $c;
}
}
else {
$result = $str;
from_to( $result, "utf-8", "big5" );
}
return $result;
}
※ 引述《StarTouching (抚星)》之铭言:
: 我现在在玩HTML Parser模组
: 不过我发现我抓完网页尝试印出某些资料时出现这个讯息:
: "\x{00a0}" does not map to big5-eten at.....
: 我查了一下 00a0在unicode中是 「无断行空格」
: big5疑似不支援
: 我的Perl档开头有加
: use encoding 'big5', Filter=>1;
: 其实我看不懂这行的细节, 只是抄骆马书翻译者的译注。
: 我想问, 我自己想到几个解决方向 何者可行?
: 1.
: 让整个perl都支援unicode, 但对parse网页来说 可能需要进一步判断网页编码
: 另外parser本身是否可以判读unicode也可能会是在我们无力控制的范围
: 2.
: 只要能在程式中能识别出这样的内码, 那麽我们就可以选择 避开
: 或是以big5既有的字符取代印出 (例如以一般空格取代无断行空格)
: 我测试了 s/\x{00a0}// 可以成功
: 但会有个额外的问题:
: 这个做法能延伸到unicode的一段范围吗?
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.114.64.130
1F:推 cutecpu:推 03/22 16:23
2F:推 StarTouching:好像要多 use Encode; 才能运作 03/22 18:03
3F:推 StarTouching:from_to 要引用甚麽模组啊? 03/22 19:21