Python中文编码判别及转换
生活随笔
收集整理的這篇文章主要介紹了
Python中文编码判别及转换
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
為什么80%的碼農都做不了架構師?>>> ??
養成使用utf8格式的習慣,但是不能保證所有的代碼都是utf8格式,所以這里提供三個函數
getCoding tran2UTF8 tran2GBK ,分別是查看編碼格式,轉換為utf8,gbk格式,加入你的輸出是亂碼,可以重定向出來,使用notepad++查看,調整編碼,直到看到的中文正常,比如,以ANSI編碼時發現中文顯式正常,說明輸出是ansi格式,而中文是不可能用ansi碼表示的,所以判斷其格式是unicode:
def?getCoding(strInput):'''獲取編碼格式'''if?isinstance(strInput,?unicode):return?"unicode"try:strInput.decode("utf8")return?'utf8'except:passtry:strInput.decode("gbk")return?'gbk'except:passdef?tran2UTF8(strInput):'''轉化為utf8格式'''strCodingFmt?=?getCoding(strInput)if?strCodingFmt?==?"utf8":return?strInputelif?strCodingFmt?==?"unicode":return?strInput.encode("utf8")elif?strCodingFmt?==?"gbk":return?strInput.decode("gbk").encode("utf8")def?tran2GBK(strInput):'''轉化為gbk格式'''strCodingFmt?=?getCoding(strInput)if?strCodingFmt?==?"gbk":return?strInputelif?strCodingFmt?==?"unicode":return?strInput.encode("gbk")elif?strCodingFmt?==?"utf8":return?strInput.decode("utf8").encode("gbk")相關資料:http://my.oschina.net/u/993130/blog/199214
轉載于:https://my.oschina.net/sanpeterguo/blog/209134
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的Python中文编码判别及转换的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysqldump 的常用参数。
- 下一篇: python第七天--字符串的方法与注释