代码艺术家
Code artist

很喜欢释迦牟尼佛的一句话:“无论你遇见谁,他都是你生命该出现的人,绝非偶然,他一定教会你一些什么”。

有问题 问我 问Google

转码问题

---恢复内容开始---

有四五天没写博客了,实在没内容写了,最近在写一个sgml东东,转码问题让我很是头疼!!!整理了一下所有转码方法,虽然最后也没成功吧,可能是系统设置的问题!

方法1

enca用法如下:

enca -L zh_CN file 检查文件的编码

enca -L zh_CN -x UTF-8 file 将文件编码转换为"UTF-8"编码

enca -L zh_CN -x UTF-8 file1 file2 如果不想覆盖原文件可以这样

除了有检查文件编码的功能以外,”enca”还有一个好处就是如果文件本来就是你要转换的那种编码,它不会报错,还是会print出结果来, 而”iconv”则会报错。这对于脚本编写是比较方便的事情。

转换单个文件的编码

enca -L none -x utf-8  index.html

方法2

通过iconv这个命令,通过file  -i  filename 或 则 file  filename  检查文件的编码

iconv  -f 原编码 -t 目的编码 文件名   转碼后会把文件内容输入到终端

iconv  -f 原编码 -o 目的编码 文件名  不会把转碼的内容输入到终端,

方法3

递归转换(包括子文件夹)
find default -type d -exec mkdir -p utf/{} \;
find default -type f -exec iconv -f GBK -t UTF-8 {} -o utf/{} \;

这两行命令将default目录下的文件由GBK编码转换为UTF-8编码,目录结构不变,转码后的文件保存在utf/default目录下。

注意:如果原来就是utf-8编码,使用iconv -f GBK -t UTF-8命令转换后,会出现乱码,或截断等各种问题;
一定要保证原文件是不是utf-8编码;


使用如下命令把文件编码先查出来:
find default -type f -exec file -i {} \; > /tmp/a
查询是否存在已经是utf-8编码的文件:
grep "charset=utf-8" /tmp/a

方法4

比如一下文件起名叫做encondoinU2G.pl

# convert all sgml files from UTF8 to GBK

use strict;
use autodie;
use File::Copy;
use encoding "utf8";
use encoding  "gbk";

my $sourceDir = "源文件路径1";
my $targetDir = "相对于源文件目录下一个存放转码后的路径";


sub process
{
    (my $sourceFile,my $targetFile)=@_;
    #print STDERR  "$sourceFile\n";
    if (-d $sourceFile){
        mkdir $targetFile unless (-d $targetFile);
        my $handle;
        if (opendir($handle, $sourceFile)) {
            while (my $subpath = readdir($handle)) {
                 if (!($subpath =~ m/^\.$/) and !($subpath =~ m/
^(\.\.)$/)) {
                     my $sourceF = $sourceFile."/$subpath";
                     my $targetF = $targetFile."/$subpath";
                     process($sourceF,$targetF);
                 }
            }
        }
        closedir($handle);
    }elsif($sourceFile =~ /.sgml$/){
        open(FIN, "<:encoding(utf8)",$sourceFile);# or die $!;
        open(FOUT, ">:encoding(gbk)",$targetFile);# or die $!;
        while(<FIN>) {
            print FOUT $_;
        }
        close(FIN);
        close(FOUT);
    }else{
        copy $sourceFile,$targetFile ;
    }
}

process $sourceDir,$targetDir ;

 执行perl encondoinU2G.pl

这个脚本可以批量转码,而且扩展性也很強!

 

---恢复内容结束---

posted @ 2015-08-06 10:20  Jason‘  阅读(265)  评论(0编辑  收藏  举报