我有一个类似“pe%20to%C5%A3i%20mai”的字符串。当我申请的时候urllib.parse.unquote对于它,我得到“pe to \u0163i mai”。如果我试图把它写到一个文件中,我得到的是精确的符号,而不是预期的字形。在
如何将字符串转换为utf-8以便在文件中使用正确的glyph?在
编辑:我使用的是python3.2
编辑2:所以我发现urllib.parse.unquote
工作正常,而我的问题是我用yaml.dump
序列化到YAML,这似乎把事情搞砸了。为什么?在
Tags:
更新:如果输出文件是yaml文档,则可以忽略其中的
\u0163
。Unicode转义符在yaml文档中有效。在注意:最后一个例子中没有
\u
。这两行表示相同的Python字符串。在yaml.dump()
有类似的选项:allow_unicode
。将其设置为True
,以避免Unicode转义。在url正确。你不需要做任何事情:
^{pr2}$\u0163
序列可能由字符编码错误处理程序引入:或者:
更多示例:
使用
unicode_escape
尝试decode
。在例如:
Python 3
调用
urllib.parse.unquote
已返回Unicode字符串:如果没有得到这个结果,那一定是代码中的错误。请张贴您的代码。在
Python 2
使用
^{pr2}$decode
从bytestring获取Unicode字符串:请记住,当您将Unicode字符串写入文件时,必须再次对其进行编码。您可以选择以UTF-8的形式写入文件,但如果需要,也可以选择不同的编码方式。您还必须记住在从文件读回时使用相同的编码。您可能会发现
codecs
模块对于在读写文件时指定编码很有用。在一个可能令人困惑的问题是,在交互式解释器中,Unicode字符串有时使用
\uxxxx
符号而不是实际字符来显示:这并不意味着字符串是“错误的”。这就是翻译的工作方式。在
相关问题 更多 >
编程相关推荐