Home Backend Development Python Tutorial python轻松实现代码编码格式转换

python轻松实现代码编码格式转换

Jun 10, 2016 pm 03:16 PM
python coding Convert

  最近刚换工作不久,没太多的时间去整理工作中的东西,大部分时间都在用来熟悉新公司的业务,熟悉他们的代码框架了,最主要的是还有很多新东西要学,我之前主要是做php后台开发的,来这边之后还要把我半路出家的前端学好、还要学习C++,哈哈,总之很充实了,每天下班回家都可以睡的很香(一句话总结,就是吃得香、睡的香~)。再说说换工作时候吧,今年年初正式毕业半年了,感觉自己技术增长很快,原公司里面程序员的地位还不如运营,所以想换个工作,面试了3家(2家大的、一家小的),都给offer了,当然从大公司里面挑了个各方面综合(工资、干什么、交通等等)还不错的,反正感觉就很顺利的进来了(比毕业的时候容易多了),哈哈,越努力、越幸运,越幸运、越努力!。从这周开始,继续整理博客,免得给自己造成懒得习惯。

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

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

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

以上就是本文所述的全部内容了,希望对大家学习python能够有所帮助。

请您花一点时间将文章分享给您的朋友或者留下评论。我们将会由衷感谢您的支持!

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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1663
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

See all articles