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

标签 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点(目的地)?

最佳答案

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。 SO 上不时会出现这样的问题:“什么编解码器将这个 str 对象转换为那个 unicode 对象?”。这是一个小脚本,可以帮助快速回答这些问题(它只是尝试使用每种可能的编码来解码 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 后,输入 str 对象的 repr:

% guess_encoding.py
\xe3\xc7\x9f

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

既然您告诉我们所需的 unicode 对象是

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

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

Decoding with cp1256:
ماں

关于Python字符串转换(本地化)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6720208/

相关文章:

python - 正则表达式从字符串中删除 'by'

Python 3.x 请求使用 unicode 字符进行重定向

java - 跨平台 unicode 支持

python - python 2.x 与 3.x 中的正则表达式 unicode

asp.net - 从 asp.net 4 中的资源文件获取文本

python - 引用列表项作为排序 for 循环中的键

python - 收集和报告 pytest 结果

python - 将 dict 转换为 tweepy 状态

c# - 是否有用于从代码文件中的字符串填充资源文件的 Visual Studio 加载项?

ios - Swift 包管理器中的可本地化字符串