python 获取系统相关编码的函数
怎么避免UnicodeEncodeError: ‘a(chǎn)scii’ codec can’t…類似的錯(cuò)誤?
1、首先在py文件頭部指定文件內(nèi)容編碼,例如:# coding: utf8
2、文件保存的時(shí)候要和py文件頭部編碼一致
3、在用decode和encode的時(shí)候,一定要確認(rèn)要轉(zhuǎn)換的字符原編碼是什么。
例如:網(wǎng)頁(yè)中都會(huì)指定編碼(<meta http-equiv=content-type content=”text/html; charset=gb2312″>), 你在抓取這個(gè)網(wǎng)站并獲取它的html后進(jìn)行編碼轉(zhuǎn)化就要注意了:
import urllib2
html = urllib2.urlopen(url)
html = html.decode(‘gb2312′)
只要做上面三個(gè)就不會(huì)出現(xiàn)轉(zhuǎn)換編碼錯(cuò)誤了
python建議,在python代碼中最好所有變量都是unicode;???? 流程可以這么寫(xiě): 變量(轉(zhuǎn)換成unicode)——>python代碼——–>變量(轉(zhuǎn)換成其他編碼)
sys.getdefaultencoding():系統(tǒng)的缺省編碼(一般就是ascii),python默認(rèn)語(yǔ)言的編碼是ascii編碼, 這就是為什么在py文件的頭部都要指定編碼了# coding:utf-8
Python獲取系統(tǒng)編碼參數(shù)的幾個(gè)函數(shù)
系統(tǒng)的缺省編碼(一般就是ascii):sys.getdefaultencoding()?
系統(tǒng)當(dāng)前的編碼:locale.getdefaultlocale()?
系統(tǒng)代碼中臨時(shí)被更改的編碼(通過(guò)locale.setlocale(locale.LC_ALL,“zh_CN.UTF-8″)):locale.getlocale()?
文件系統(tǒng)的編碼:sys.getfilesystemencoding()?
終端的輸入編碼:sys.stdin.encoding?
終端的輸出編碼:sys.stdout.encoding?
代碼的缺省編碼:文件頭上# -*- coding: utf-8 –*-
來(lái)源:http://justpy.com/archives/144
(二)
更多:
http://www.cnblogs.com/itrust/archive/2010/05/14/1735185.html
字符串
python有兩種字符串
| 1 2 | byteString =?"hello world! (in my default locale)" unicodeString =?u"hello Unicode world!" |
相互轉(zhuǎn)換
| 1 2 3 4 | 1?s =?"hello normal string" 2?u =?unicode( s, "utf-8"?) 3?backToBytes =?u.encode( "utf-8"?) 3?backToUtf8 =?backToBytes.decode(‘utf-8’) #與第二行效果相同 |
如何判斷
| 1 2 3 | if?isinstance( s, str?): # 對(duì)Unicode strings,這個(gè)判斷結(jié)果為False if?isinstance( s, unicode): # 對(duì)Unicode strings,這個(gè)判斷結(jié)果為T(mén)rue if?isinstance( s, basestring?): # 對(duì)兩種字符串,返回都為T(mén)rue |
做個(gè)試驗(yàn)
| 1 2 3 4 5 6 | import?sys print?'default encoding: '?, sys.getdefaultencoding() print?'file system encoding: '?, sys.getfilesystemencoding() print?'stdout encoding: '?, sys.stdout.encoding print?u'u"中文" is unicode: ', isinstance(u'中文',unicode) print?u'"中文" is unicode: ', isinstance('中文',unicode) |
看輸出結(jié)果,注意下列事實(shí):
python系統(tǒng)缺省的編碼格式為ASCII,這個(gè)缺省編碼在Python轉(zhuǎn)換字符串時(shí)用的到,這里給兩個(gè)例子:
1. a = "abc" + u"bcd", Python會(huì)如此轉(zhuǎn)換"abc".decode(sys.getdefaultencoding()) 然后將兩個(gè)Unicode字符合并。
2. print unicode('中文') , 這句話執(zhí)行會(huì)出錯(cuò)“UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 …”,是因?yàn)镻ython試圖用缺省編碼來(lái)編碼,而這個(gè)字符串不是ASCII,因此需要顯示的指出,如果你的文件源類型為utf-8,則應(yīng)如此:print unicode('中文','utf-8’)
Windows下getfilesystemencoding輸出mbcs(多字節(jié)編碼,windows的mbcs,也就是ansi,它會(huì)在不同語(yǔ)言的windows中使用不同的編碼,在中文的windows中就是gb系列的編碼)
Windows下控制臺(tái)編碼為cp936, 當(dāng)你打印東西到控制臺(tái)時(shí)Python自動(dòng)做了轉(zhuǎn)換。這里會(huì)引發(fā)一個(gè)有趣的問(wèn)題, 試一下這個(gè)簡(jiǎn)單的例子test.py:
| 1 2 3 | # -*- coding: utf-8 -*- s =?u'中文' print?s |
在控制臺(tái)中分別運(yùn)行 python test.py 和 python test.py > 1.txt
你會(huì)發(fā)現(xiàn)后者會(huì)報(bào)錯(cuò),原因是打印控制臺(tái)時(shí)Python會(huì)自動(dòng)轉(zhuǎn)換編碼到sys.stdout.encoding, 而輸出到文件時(shí)Python不會(huì)自動(dòng)在write調(diào)用中進(jìn)行內(nèi)部字符轉(zhuǎn)換。這個(gè)問(wèn)題在PrintFails中有較詳細(xì)的說(shuō)明。
UTF-8編碼格式
保存utf-8格式的文件
| 1 2 3 | import?codecs fileObj =?codecs.open( "someFile", "r", "utf-8"?) u =?fileObj.read() # Returns a Unicode string from the UTF-8 bytes in the file |
自己寫(xiě)B(tài)OM頭
| 1 2 3 4 | out =?file( "someFile", "w"?) out.write( codecs.BOM_UTF8 ) out.write( unicodeString.encode( "utf-8"?) ) out.close() |
自己去掉BOM頭
對(duì)UTF-16, Python將BOM解碼為空字串。然而對(duì)UTF-8, BOM被解碼為一個(gè)字符,如例:
| 1234 | >>> codecs.BOM_UTF16.decode( "utf16"?) u'' >>> codecs.BOM_UTF8.decode( "utf8"?) u'\ufeff' |
不知道為什么會(huì)這樣不同,因此你需要在讀文件時(shí)自己去掉BOM:
| 1 2 3 4 5 6 7 8 9 10 11 | import codecs if?s.beginswith( codecs.BOM_UTF8?): ????# The byte string s begins with the BOM: Do something. ????# For example, decode the string as UTF-8 ????? if?u[0] == unicode( codecs.BOM_UTF8, "utf8"?): ????# The unicode string begins with the BOM: Do something. ????# For example, remove the character. # Strip the BOM from the beginning of the Unicode string, if it exists u.lstrip( unicode( codecs.BOM_UTF8, "utf8"?) ) |
源碼文件的編碼
關(guān)于Python對(duì)代碼文件的編碼處理,PEP0263?講的很清楚,現(xiàn)摘錄如下
python缺省認(rèn)為文件為ASCII編碼。
可在代碼頭一行或二行加入聲明文件編碼申明,通知python該文件的編碼格式,如
???? # -*- coding: utf-8 –*-?? # 注意使用的編輯器,確保文件保存時(shí)使用了該編碼格式
- 如果文件中沒(méi)有編碼申明,python以u(píng)tf8處理
- 如果有編碼申明但不是utf-8, python報(bào)錯(cuò)
==============另外,關(guān)于BOM================
(三)
某些軟件,如notepad,在保存一個(gè)以UTF-8編碼的文件時(shí),會(huì)在文件開(kāi)始的地方插入三個(gè)不可見(jiàn)的字符(0xEF 0xBB 0xBF,即BOM)。?
因此我們?cè)谧x取時(shí)需要自己去掉這些字符,python中的codecs module定義了這個(gè)常量:?
| 1 2 3 4 5 6 | # coding=gbk import?codecs data =?open("Test.txt").read() if?data[:3] ==?codecs.BOM_UTF8: ?data =?data[3:] print?data.decode("utf-8") |
總結(jié)
以上是生活随笔為你收集整理的python 获取系统相关编码的函数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: PYTHON-进阶-编码处理小结
- 下一篇: getopt在Python中的使用