Vit*_*biy 4 python unicode character-encoding
有没有办法可以为python添加别名进行编码.网上有网站使用编码'windows-1251',但他们的字符集设置为win-1251,所以我想让win-1251成为windows-1251的别名
该encodings模块没有很好的文档,所以我改为使用codecs,这是:
import codecs
def encalias(oldname, newname):
old = codecs.lookup(oldname)
new = codecs.CodecInfo(old.encode, old.decode,
streamreader=old.streamreader,
streamwriter=old.streamwriter,
incrementalencoder=old.incrementalencoder,
incrementaldecoder=old.incrementaldecoder,
name=newname)
def searcher(aname):
if aname == newname:
return new
else:
return None
codecs.register(searcher)
Run Code Online (Sandbox Code Playgroud)
这是Python 2.6 - 早期版本的界面不同.
如果您不介意依赖特定版本的无证内部,@ Lennart的别名方法当然也可以 - 而且确实比这更简单;-).但我怀疑(他似乎)这个更易于维护.
>>> import encodings
>>> encodings.aliases.aliases['win_1251'] = 'cp1251'
>>> print '\xcc\xce\xd1K\xc2\xc0'.decode('win-1251')
MOCKBA
Run Code Online (Sandbox Code Playgroud)
虽然我个人会考虑这个猴子修补,并使用我自己的转换表.但我不能对这个立场提出任何好的论据.:)