Python字符串转换(本地化)问题

时间:2011-07-16 21:02:50

标签: python unicode localization

source = '\xe3\xc7\x9f'
destination = u'\u0645\u0627\u06ba'

如何从源头到达目的地?

(来源和目的地都是相同的3个字符,顺序相同,只是表示不同。)

从技术上讲,源是在乌尔都语中,目标是相同3个字符的Unicode代码点。请参阅:https://www.codeaurora.org/git/projects/froyo-gb-dsds-7227/repository/revisions/39141d7a9dbdd2e9acf006430a7e7557ffd1efce/entry/external/icu4c/data/mappings/ibm-5352_P100-1998.ucm

如果我这样做:

source.decode('cp1006')

我明白了:

u'\ufed9\ufb84\x9f'

这不是我想要的......

如果我这样做:

source.decode('raw_unicode_escape')

我明白了:

u'\xe3\xc7\x9f'

这也不是我想要的......

如何在Python中从A点(源)到B点(目标)?

1 个答案:

答案 0 :(得分:6)

In [129]: source = '\xe3\xc7\x9f'
In [130]: source.decode('cp1256')
Out[130]: u'\u0645\u0627\u06ba'

In [131]: destination
Out[131]: u'\u0645\u0627\u06ba'

PS。问题“什么编解码器将此str对象转换为该unicode对象?”不时出现在SO上。这是一个小脚本,可以帮助快速回答这些问题(它只是尝试使用每种可能的编码解码str对象):

guess_encoding.py:

import binascii
import zlib
import codecs
import pkgutil
import os
import encodings

def all_encodings():
    modnames=set([modname for importer, modname, ispkg in pkgutil.walk_packages(
        path=[os.path.dirname(encodings.__file__)], prefix='')])
    aliases=set(encodings.aliases.aliases.values())
    return modnames.union(aliases)        

def main():
    encodings=all_encodings()
    while 1:
        text=raw_input()
        text=codecs.escape_decode(text)[0]
        # print('Attempting to decode {0!r}'.format(text))
        for enc in encodings:
            try:
                msg=text.decode(enc)
            except (IOError,UnicodeDecodeError,LookupError,
                    TypeError,ValueError,binascii.Error,zlib.error) as err:
                pass
                # print('{e} failed: {err}'.format(e=enc,err=err))
            else:
                if msg:
                    print('Decoding with {enc}:'.format(enc=enc))
                    print(msg)

if __name__=='__main__':
    main()

运行guess_encoding.py后,您输入repr对象的str

% guess_encoding.py
\xe3\xc7\x9f

它针对每种可能的Python编码吐出相关的unicode对象。

因为你告诉我们所需的unicode对象是

In [128]: print(destination)
ماں

您可以快速搜索输出 ماں并找到成功的编解码器:

Decoding with cp1256:
ماں