python中的代码编码格式转换问题

WBOY
Release: 2016-06-10 15:10:41
Original
925 people have browsed it

  刚来这个公司,熟悉了环境,老大就开始让我做一个迁移、修改代码的工作,我想说的是,这种工作真没劲~~,看别人的代码、改别人的代码、这里改个变量、那里改个文件名······,都是些没技术含量、很繁琐的事情,不过通过迁移代码顺便熟悉下环境也好。扯了这么多,说说今天的主题吧——代码编码格式改变,由于某些原因,需要将代码从A机房迁移到B机房,这两个之间不能互相访问,但是历史原因导致A机房的代码全是utf8编码的,B机房要求是GBK编码,看看这个怎么解决。

编码问题

  先说说为什么会有编码问题,就拿上面那个例子来说,B机房这边数据库全是GBK编码的,因此从数据库中取出来的数据都是GBK的,从数据库中取出来的数据是GBK编码的,要在展示的时候不乱码,在不对数据库取出的数据转换的情况下,就需要发送header的时候设置编码为GBK,输出的文件(html、tpl等)都必须是GBK的,看看下面这个图会更清楚点:

    DB(GBK) => php等(编码格式不限但如果代码文件中有汉字,文件就要是gbk编码或者在汉字输出的时候转化为gbk) => header(GBK)  => html、tpl(GBK)

  或者还有一种方式只在出库的时候在代码中将utf8转化为gbk,总的来说utf8还是更流行点,问题更少点

    DB(GBK) => php等(utf8,并将从数据库取出的数据转化为utf8) => header(utf8) => html、tpl(utf8)

  只要按照上面这两种规范编码格式,就不会出现乱码情况,起码我测试的第一种方式是没问题的,所以我猜第二种也ok,好了,现在就来写一个转换文件编码格式的小脚本:

#!/usr/bin/python
# -*- coding: utf-8 -*-
#Filename:changeEncode.py
import os
import sys

def ChangeEncode(file,fromEncode,toEncode):
  try:
    f=open(file)
    s=f.read()
    f.close()
    u=s.decode(fromEncode)
    s=u.encode(toEncode)
    f=open(file,"w");
    f.write(s)
    return 0;
  except:
    return -1;

def Do(dirname,fromEncode,toEncode):
  for root,dirs,files in os.walk(dirname):
    for _file in files:
      _file=os.path.join(root,_file)
      if(ChangeEncode(_file,fromEncode,toEncode)!=0):
        print "[转换失败:]"+_file
      else:
        print "[成功:]"+_file

def CheckParam(dirname,fromEncode,toEncode):
  encode=["UTF-8","GBK","gbk","utf-8"]
  if(not fromEncode in encode or not toEncode in encode):
    return 2
  if(fromEncode==toEncode):
    return 3
  if(not os.path.isdir(dirname)):
    return 1
  return 0

if __name__=="__main__":
  error={1:"第一个参数不是一个有效的文件夹",3:"源编码和目标编码相同",2:"您要转化的编码不再范围之内:UTF-8,GBK"}
  dirname=sys.argv[1]
  fromEncode=sys.argv[2]
  toEncode=sys.argv[3]
  ret=CheckParam(dirname,fromEncode,toEncode)
  if(ret!=0):
    print error[ret]
  else:
    Do(dirname,fromEncode,toEncode)

Copy after login

  脚本很简单,使用也很简单

复制代码 代码如下:

  ./changeEncode.py target_dir fromEncode toEncode

  这里要注意下,几种常见编码的关系:

  us-ascii编码是utf-8编码的一个子集,这个是从stackoverflow上得到的,原文如下ASCII is a subset of UTF-8, so all ASCII files are already UTF-8 encoded,

我试了下确实是的,在不加汉字的时候显示编码为us-ascii,加了汉字之后,变为utf-8。

  还有就是ASNI编码格式,这代表是本地编码格式,比如说在简体中文操作系统下,ASNI编码就代表GBK编码,这点还需要注意

  还有一点就是一个在linux下查看文件编码格式的命令是:

file -i *

  可以看到文件的编码格式。

  当然了,上面的可能有些文件中有特殊字符,处理的时候会失败,但一般程序文件是没有问题的。

以上所述就是本文的全部内容了,希望大家能够喜欢。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!