使用 YAML 转储 unicode

Dumping unicode with YAML

我正在从 csv 创建 yaml 文件,其中有很多 unicode 字符,但我似乎无法在不给我解码错误的情况下转储 unicode。

我正在使用 ruamel.yaml 库。

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 11: ordinal not in range(128)

我试过解析字符串、unicode 字符串、使用 "utf-8" 编码似乎都没有用。我已经看到很多示例显示添加代表来解决问题,但他们似乎都在使用 ruamel 的旧方法,我似乎无法在任何地方记录的新方法中找到如何做到这一点。

from ruamel.yaml import YAML

class YamlObject(YAML):
    def __init__(self):
        YAML.__init__(self)
        self.default_flow_style = False
        self.block_seq_indent = 2
        self.indent = 4
        self.allow_unicode = True

textDict = {"text": u"HELLO_WORLD©"}
textFile = "D:\testFile.yml"
yaml = YamlObject()
yaml.dump(textDict, file(textFile, "w"))

我可以对整个 dict 进行 unicode 编码,这很有效,但它没有给我返回我需要的格式。

我需要的只是:

text: HELLO_WORLD©

我该怎么做?

您的派生 YAML 对象中缺少 encoding

这样试试:

class YamlObject(YAML):
    def __init__(self):
        YAML.__init__(self)
        self.default_flow_style = False
        self.block_seq_indent = 2
        self.indent = 4
        self.allow_unicode = True
        self.encoding = 'utf-8'

如果你 look at the definition of your base class, YAML,你会注意到默认情况下,encoding 是未定义的:

self.encoding = None

并通过YAML.dump() and YAML.dump_all(). In the global dump()方法保持None,相反,encoding设置为默认utf-8(仅在Python 2中)。

更新。这实际上是 ruamel.yaml 中 Python 2 的错误(感谢@Anthon)。