mim*_*imo 5 python encoding utf-8 iso-8859-1
有谁知道Python 库可以让您以智能方式将UTF-8 字符串转换为ISO-8859-1 编码?
\n\n所谓聪明,我的意思是用“-”左右替换“\xe2\x80\x93”等字符。对于许多确实无法想到等效字符的字符,请替换为“?” (就像encode(\'iso-8859-1\', errors=\'replace\')那样)。
由于 Unicode 的前 256 个代码点与 ISO-8859-1 匹配,因此可以尝试编码为 ISO-8859-1,它将处理 0 到 255 的所有字符而不会出现错误。对于导致编码错误的字符,可以使用unidecode。
\n\n以下内容适用于 Python 2 和 3:
\n\nfrom builtins import str\nimport unidecode\n\ndef unidecode_fallback(e):\n part = e.object[e.start:e.end]\n replacement = str(unidecode.unidecode(part) or '?')\n return (replacement, e.start + len(part))\n\ncodecs.register_error('unidecode_fallback', unidecode_fallback)\n\ns = u'abcd\xc3\xa9\xe2\x80\x93fghijkl'.encode('iso-8859-1', errors='unidecode_fallback')\nprint(s.decode('iso-8859-1'))\nRun Code Online (Sandbox Code Playgroud)\n\n结果:
\n\nabcd\xc3\xa9-fgh?ijkl\nRun Code Online (Sandbox Code Playgroud)\n\n然而,这会将非 ISO-8859-1 字符转换为 ASCII 等效字符,而有时使用非 ASCII、ISO-8859-1 等效字符可能会更好。
\n| 归档时间: |
|
| 查看次数: |
6687 次 |
| 最近记录: |