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 贴的代码实在是太难看了,可以在这里 下载。有时间一定的好好整整它,哼!