本站首页    管理页面    写新日志    退出


«October 2025»
1234
567891011
12131415161718
19202122232425
262728293031


公告
 本博客在此声明所有文章均为转摘,只做资料收集使用。

我的分类(专题)

日志更新

最新评论

留言板

链接

Blog信息
blog名称:
日志总数:1304
评论数量:2242
留言数量:5
访问次数:7627774
建立时间:2006年5月29日




[Python]一个批量转换文本文件编码的程序(Python)
软件技术

lhwork 发表于 2007/2/1 9:06:53

这个其实很简单的,用 decode() 和 和 encode 两个函数就可以搞定。 我需要的是 GB2312 跟 UTF-8 之间的转换,需要 Python 2.4 或者 Python 2.3 + CJKCodecs,要不然不支持 GB2312 的编码 用 GB2312 时,有时会出现错误,说某个字符不能识别,估计是超出了它的字符集的原因,由于 GBK 是它的扩展,索性就直接用 GBK 了。 此外就是目录遍历了,有一个非常好的工具 os.walk(),一次搞定。 完整的源代码如下: undefinedview plaincopy to clipboardprint? #!/usr/bin/python       import os,sys      def convert( filename, in_enc = "GBK", out_enc="UTF-8" ):        # read the file        content = open( filename ).read()        # convert the concent        try:            new_content = content.decode( in_enc ).encode( out_enc )            #write to file            open( filename, 'w' ).write( new_content )        except:            print " error... "       def explore( dir ):        for root, dirs, files in os.walk( dir ):            for file in files:                path = os.path.join( root, file )                print "convert " + path,                convert( path )                print " done"       def main():        if len( sys.argv ) > 1 :            path = sys.argv[1]            if os.path.isfile( path ):                convert( path )            elif os.path.isdir( path ):                explore( path )       if __name__ == "__main__":        main()    #!/usr/bin/python import os,sys def convert( filename, in_enc = "GBK", out_enc="UTF-8" ): # read the file content = open( filename ).read() # convert the concent try: new_content = content.decode( in_enc ).encode( out_enc ) #write to file open( filename, 'w' ).write( new_content ) except: print " error... " def explore( dir ): for root, dirs, files in os.walk( dir ): for file in files: path = os.path.join( root, file ) print "convert " + path, convert( path ) print " done" def main(): if len( sys.argv ) > 1 : path = sys.argv[1] if os.path.isfile( path ): convert( path ) elif os.path.isdir( path ): explore( path ) if __name__ == "__main__": main() 这个 Blog 贴的代码实在是太难看了,可以在这里 下载。有时间一定的好好整整它,哼!


阅读全文(3836) | 回复(0) | 编辑 | 精华
 



发表评论:
昵称:
密码:
主页:
标题:
验证码:  (不区分大小写,请仔细填写,输错需重写评论内容!)



站点首页 | 联系我们 | 博客注册 | 博客登陆

Sponsored By W3CHINA
W3CHINA Blog 0.8 Processed in 0.047 second(s), page refreshed 144790843 times.
《全国人大常委会关于维护互联网安全的决定》  《计算机信息网络国际联网安全保护管理办法》
苏ICP备05006046号