如何匹配charset为big5(Perl)的网页中的汉字?

时间:2012-06-22 10:03:54

标签: perl

我在中文单词之间进行匹配,例如“语言中心”和一系列网络文件(php,html,htm等)。

然而,不知何故,我收到以下错误:

Malformed UTF-8 character (1 byte, need 2, after start byte 0xdf) in regexp compilation at ../Final_FindOnlyNoReplace_CLE_Chinese.pl line 89, <INFILE> line 12.

有人可以帮忙吗?

这是我的代码。

#!/usr/bin/env perl
use Encode qw/encode decode/;

use utf8;
use strict;
use Cwd;
use LWP::UserAgent;

my($path) = @_;

## append a trailing / if it's not there
$path .= '/' if($path !~ /\/$/);

use File::Glob ':glob';

my @all_files = bsd_glob($path."*");

for my $eachFile (@all_files) {
    open(INFILE, "<$eachFile") || die ("Could not open '$eachFile'\n");

    my(@inlines) = <INFILE>;
    my($line, $find);
    my $outkey = 1;

    foreach $line (@inlines) {
        $find = &find($line);
        if ($find ne 'false') {
            chomp($line);
            print "\tline$outkey : $line\n"; 
        }
        $outkey ++;
    }
}

#subroutine
sub find {
    my $m = encode("utf8", decode("big5", @_));

    my $html = LWP::UserAgent->new
        ->get($m)
        ->decoded_content;
    my $str_chinese = '語言中心';

    if ($m =~ /$str_chinese/) {  
        $m; ##if match, return the whole line.
    }
}   

2 个答案:

答案 0 :(得分:0)

您没有在$html中搜索和解码,而是在网址中搜索:$m =~ /$str_chinese/,我猜,这不是您想要的。

另外,您将find函数的结果与精确字符串“false”进行比较,这将永远不会起作用。将if ($find ne 'false')更改为if (defined($find)),并为find添加明确的成功和失败回报。

最后,您的脚本似乎失败了,因为您将其指向其他文件中包含其他Perl脚本的目录。它们很可能是UTF-8,所以当你的脚本试图将它们作为big5数据读取时,它就会在解码时失败。只需更改您的glob即可覆盖数据文件。

答案 1 :(得分:0)

#!/usr/bin/env perl
use utf8;
use strictures;
use LWP::UserAgent qw();
use Path::Class::Rule qw();
use URI::file qw();

my $start_directory = q(.);
my $search_text = qr'語言中心';

my $next = Path::Class::Rule->new->name(qw(*.php *.htm*))->iter($start_directory);

my @matching_lines;
while (my $file = $next->()) {
    for my $line (split /\R/, LWP::UserAgent
        ->new
        ->get(URI::file->new_abs($file))
        ->decoded_content
    ) {
        push @matching_lines, $line if $line =~ $search_text;
    }
}
# @matching_lines is (
#     '<title>Untitled 語言中心 Document</title>',
#     'abc 語言中心 cde',
#     '天天向上語言中心他'
# )