Adding encoding alias to python

后端 未结 3 1490
不知归路
不知归路 2021-01-06 11:59

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, s

3条回答
  •  礼貌的吻别
    2021-01-06 12:54

    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)
    

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

    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.

提交回复
热议问题