向python添加编码别名 [英] Adding encoding alias to python

查看:45
本文介绍了向python添加编码别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以向python添加别名进行编码。网络上有一些网站使用的编码为 windows-1251,但其字符集设置为win-1251,所以我想将win-1251用作Windows-1251的别名

Is there a way that I can add alias to python for encoding. There are sites on the web that are using the encoding 'windows-1251' but have their charset set to win-1251, so I would like to have win-1251 be an alias to windows-1251

推荐答案

encodings 模块的文档不完整,因此我将使用 codecs

The encodings module is not well documented so I'd instead use codecs, which is:

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)

这是Python 2.6-界面有所不同

This is Python 2.6 -- the interface is different in earlier versions.

如果您不介意使用特定版本的未记录内部结构,@ Lennart的别名处理当然也可以-确实比这更简单; -)。但我怀疑(正如他看来的那样)这一点更容易维护。

If you don't mind relying on a specific version's undocumented internals, @Lennart's aliasing approach is OK, too, of course - and indeed simpler than this;-). But I suspect (as he appears to) that this one is more maintainable.

这篇关于向python添加编码别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆