gpt4 book ai didi

python - 在 Python 2 + GTK 中检测/删除未配对的代理字符

转载 作者:太空狗 更新时间:2023-10-29 21:40:12 27 4
gpt4 key购买 nike

在 Python 2.7 中,我可以成功地将 Unicode 字符串 "abc\udc34xyz" 转换为 UTF-8(结果是 "abc\xed\xb0\xb4xyz")。但是当我将 UTF-8 字符串传递给例如时。 pango_parse_markup()g_convert_with_fallback(),我收到类似“转换输入中的字节序列无效”的错误。显然,GTK/Pango 函数检测到字符串中的“不成对代理项”并(正确地?)拒绝它。

Python 3 甚至不允许将 Unicode 字符串转换为 UTF-8(错误:“‘utf-8’编解码器无法在位置 3 中编码字符‘\udc34’:不允许代理”),但我可以运行 "abc\udc34xyz".encode("utf8", "replace") 以获取有效的 UTF8 字符串,其中单独的代理项替换为其他字符。这对我来说很好,但我需要一个适用于 Python 2 的解决方案。

所以问题是:在 Python 2.7 中,我如何才能将该 Unicode 字符串转换为 UTF-8,同时用 U+FFFD 等替换字符替换单独的代理项?最好只使用标准 Python 函数和 GTK/GLib/G... 函数。

顺便说一句。 Iconv 可以将字符串转换为 UTF8,但只是删除坏字符而不是用 U+FFFD 替换它。

最佳答案

你可以在编码之前自己做替换:

import re

lone = re.compile(
ur'''(?x) # verbose expression (allows comments)
( # begin group
[\ud800-\udbff] # match leading surrogate
(?![\udc00-\udfff]) # but only if not followed by trailing surrogate
) # end group
| # OR
( # begin group
(?<![\ud800-\udbff]) # if not preceded by leading surrogate
[\udc00-\udfff] # match trailing surrogate
) # end group
''')

u = u'abc\ud834\ud82a\udfcdxyz'
print repr(u)
b = lone.sub(ur'\ufffd',u).encode('utf8')
print repr(b)
print repr(b.decode('utf8'))

输出:

u'abc\ud834\U0001abcdxyz'
'abc\xef\xbf\xbd\xf0\x9a\xaf\x8dxyz'
u'abc\ufffd\U0001abcdxyz'

关于python - 在 Python 2 + GTK 中检测/删除未配对的代理字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18673213/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com