search
HomeBackend DevelopmentPython Tutorialpython中的代码编码格式转换问题

  刚来这个公司,熟悉了环境,老大就开始让我做一个迁移、修改代码的工作,我想说的是,这种工作真没劲~~,看别人的代码、改别人的代码、这里改个变量、那里改个文件名······,都是些没技术含量、很繁琐的事情,不过通过迁移代码顺便熟悉下环境也好。扯了这么多,说说今天的主题吧——代码编码格式改变,由于某些原因,需要将代码从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)

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

复制代码 代码如下:

  ./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 *

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

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

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

Statement
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
Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

For loop and while loop in Python: What are the advantages of each?For loop and while loop in Python: What are the advantages of each?May 13, 2025 am 12:01 AM

Forloopsareadvantageousforknowniterationsandsequences,offeringsimplicityandreadability;whileloopsareidealfordynamicconditionsandunknowniterations,providingcontrolovertermination.1)Forloopsareperfectforiteratingoverlists,tuples,orstrings,directlyacces

Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),