看板Python
标 题Re: [问题] 请问一下unicode的问题
发信站老鼠的香香乳酪洞 (Sat Jan 6 15:07:06 2007)
转信站ptt!ctu-reader!ctu-peer!news.nctu!news.cis.nctu!Mouse
※ 引述《[email protected] (Insomnia)》之铭言:
: ※ 引述《pkyosx (Insomnia)》之铭言:
: : 直接用 Ultra Editor Hex进位模式验证:
: : 存档前:
: : => FF FE 11 62
: : 存档後: 终於发现问题就在於 notepad 存 UTF-8 的时候多存东西上去了!!
: : => FF FE FF FE 11 62
: : 但是 notepad 存 unicode(UTF-16), Ultra-Editor 存 UTF-8, UTF-16 都不会有问题
: : => FF FE 11 62
: : 结论:
: : 习惯用 notepad 开文件的人小心阿= =" ...TMD
总结一下:
BOM on wiki:
http://en.wikipedia.org/wiki/Byte_Order_Mark
UTF-8 没有 BE LE 的问题, 所以拿 BOM 只是用来跟其他编码识别
我用 hexdump 出来是 EF BB BF
用 ultra-editor 看到的却是 FF FE FF FE
但是用里面的一个 unicode/ascii/utf8 转 utf8 (ascii 编辑) 後才变成 EF BB BF
不知道聪明的 Ultra editor 到底做了什麽事情
我猜可能跟编辑的编码有关
这是另一位板友提供的连结:
http://evanjones.ca/python-utf8.html
里面一小段 code 说出了 python 在处理 utf-8 奇怪的地方
>>> codecs.BOM_UTF16.decode( "utf16" )
u''
>>> codecs.BOM_UTF8.decode( "utf8" )
u'\ufeff'
他的建议是自己在侦测到 utf-8 的时候 手动把 u'\ufeff' 拿掉
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" ) )
这是 python 的 bug 吗? 其实我不确定, 如果有人系统本身是 UTF-8 的可以试试看
搞不好 decode 出来不会多个 FEFF
--
※Post by pky from pkyosx.Dorm-GD2.NCTU.edu
老鼠的香香乳酪洞˙电子布告栏系统˙alexbbs.twbbs.org˙140.113.166.7