python轻松实现代码编码格式转换
最近刚换工作不久,没太多的时间去整理工作中的东西,大部分时间都在用来熟悉新公司的业务,熟悉他们的代码框架了,最主要的是还有很多新东西要学,我之前主要是做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)
脚本很简单,使用也很简单
./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能够有所帮助。
请您花一点时间将文章分享给您的朋友或者留下评论。我们将会由衷感谢您的支持!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to download DeepSeek Xiaomi? Search for "DeepSeek" in the Xiaomi App Store. If it is not found, continue to step 2. Identify your needs (search files, data analysis), and find the corresponding tools (such as file managers, data analysis software) that include DeepSeek functions.

The key to using DeepSeek effectively is to ask questions clearly: express the questions directly and specifically. Provide specific details and background information. For complex inquiries, multiple angles and refute opinions are included. Focus on specific aspects, such as performance bottlenecks in code. Keep a critical thinking about the answers you get and make judgments based on your expertise.

Just use the search function that comes with DeepSeek. Its powerful semantic analysis algorithm can accurately understand the search intention and provide relevant information. However, for searches that are unpopular, latest information or problems that need to be considered, it is necessary to adjust keywords or use more specific descriptions, combine them with other real-time information sources, and understand that DeepSeek is just a tool that requires active, clear and refined search strategies.

DeepSeek is not a programming language, but a deep search concept. Implementing DeepSeek requires selection based on existing languages. For different application scenarios, it is necessary to choose the appropriate language and algorithms, and combine machine learning technology. Code quality, maintainability, and testing are crucial. Only by choosing the right programming language, algorithms and tools according to your needs and writing high-quality code can DeepSeek be successfully implemented.

Question: Is DeepSeek available for accounting? Answer: No, it is a data mining and analysis tool that can be used to analyze financial data, but it does not have the accounting record and report generation functions of accounting software. Using DeepSeek to analyze financial data requires writing code to process data with knowledge of data structures, algorithms, and DeepSeek APIs to consider potential problems (e.g. programming knowledge, learning curves, data quality)

Detailed explanation of DeepSeekAPI access and call: Quick Start Guide This article will guide you in detail how to access and call DeepSeekAPI, helping you easily use powerful AI models. Step 1: Get the API key to access the DeepSeek official website and click on the "Open Platform" in the upper right corner. You will get a certain number of free tokens (used to measure API usage). In the menu on the left, click "APIKeys" and then click "Create APIkey". Name your APIkey (for example, "test") and copy the generated key right away. Be sure to save this key properly, as it will only be displayed once

PiNetwork is about to launch PiBank, a revolutionary mobile banking platform! PiNetwork today released a major update on Elmahrosa (Face) PIMISRBank, referred to as PiBank, which perfectly integrates traditional banking services with PiNetwork cryptocurrency functions to realize the atomic exchange of fiat currencies and cryptocurrencies (supports the swap between fiat currencies such as the US dollar, euro, and Indonesian rupiah with cryptocurrencies such as PiCoin, USDT, and USDC). What is the charm of PiBank? Let's find out! PiBank's main functions: One-stop management of bank accounts and cryptocurrency assets. Support real-time transactions and adopt biospecies

This article explores the quantitative trading functions of the three major exchanges, Binance, OKX and Gate.io, aiming to help quantitative traders choose the right platform. The article first introduces the concepts, advantages and challenges of quantitative trading, and explains the functions that excellent quantitative trading software should have, such as API support, data sources, backtesting tools and risk control functions. Subsequently, the quantitative trading functions of the three exchanges were compared and analyzed in detail, pointing out their advantages and disadvantages respectively, and finally giving platform selection suggestions for quantitative traders of different levels of experience, and emphasizing the importance of risk assessment and strategic backtesting. Whether you are a novice or an experienced quantitative trader, this article will provide you with valuable reference
