2

我正在从 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©

我怎样才能做到这一点?

4

1 回答 1

4

encoding在派生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
        self.encoding = 'utf-8'

如果您查看基类的定义YAML,您会注意到默认情况下encoding未定义:

self.encoding = None

并且它一直None通过YAML.dump()and YAML.dump_all()dump()相反,在全局方法中,encoding设置为默认值utf-8(仅在 Python 2 中)。

更新。这实际上是ruamel.yamlPython 2 的一个错误(感谢@Anthon)。

于 2017-07-24T13:26:37.963 回答