在 python 中编码并在 Python 中将其写入 YAML 文件

encoding in python and writing it to a YAML file in Python

我有一个 Unicode,它是从 CSV 文件中读取的:

df.iloc[0,1]
Out[41]: u'EU-repr\xe6sentant udpeget'

In [42]: type(df_translated.iloc[0,1])
Out[42]: unicode

我想把它设为 EU-repræsentant udpeget。最终目标是将其写入字典,然后使用 safe_dump 使用 PyYAML 最终将该字典保存到 YAML 文件中。但是,我在编码方面遇到了困难。

如果你真的需要使用 PyYAML,你应该提供参数 encoding='utf-8'allow_unicode=Truesafe_dump() 常规。

如果您打算升级到 YAML 1.2 并使用 ruamel.yaml (免责声明:我是那个包的作者),那些是(很多 更明智)默认值:

import sys
import ruamel.yaml

yaml = ruamel.yaml.YAML()

data = [u'EU-repr\xe6sentant udpeget']
yaml.dump(data, sys.stdout)

给出:

- EU-repræsentant udpeget