python - PyYaml - 转储带有特殊字符(即重音符号)的 unicode

标签 python unicode yaml non-ascii-characters pyyaml

我正在处理 yaml 文件,这些文件必须是人类可读和可编辑的,但也可以通过 Python 代码进行编辑。 我正在使用 Python 2.7.3

该文件需要处理重音(主要是处理法语文本)。

这是我的问题示例:

import codecs
import yaml

file = r'toto.txt'

f = codecs.open(file,"w",encoding="utf-8")

text = u'héhéhé, hûhûhû'

textDict = {"data": text}

f.write( 'write unicode     : ' + text + '\n' )
f.write( 'write dict        : ' + unicode(textDict) + '\n' )
f.write( 'yaml dump unicode : ' + yaml.dump(text))
f.write( 'yaml dump dict    : ' + yaml.dump(textDict))
f.write( 'yaml safe unicode : ' + yaml.safe_dump(text))
f.write( 'yaml safe dict    : ' + yaml.safe_dump(textDict))

f.close()

写入的文件包含:

write unicode     : héhéhé, hûhûhû
write dict        : {'data': u'h\xe9h\xe9h\xe9, h\xfbh\xfbh\xfb\n'}

yaml dump unicode : "h\xE9h\xE9h\xE9, h\xFBh\xFBh\xFB"
yaml dump dict    : {data: "h\xE9h\xE9h\xE9, h\xFBh\xFBh\xFB"}

yaml safe unicode : "h\xE9h\xE9h\xE9, h\xFBh\xFBh\xFB"
yaml safe dict    : {data: "h\xE9h\xE9h\xE9, h\xFBh\xFBh\xFB"}

yaml 转储非常适合加载 yaml,但它不是人类可读的。

正如您在示例代码中看到的,当我尝试编写一个 dict 的 unicode 表示时,结果是相同的(我不知道它是否相关)。

我希望转储包含带重音的文本,而不是 unicode 代码。 这可能吗?

最佳答案

yaml 能够通过向任何转储程序提供 allow_unicode=True 关键字参数来转储 unicode 字符。如果您不提供文件,您将从 dump() 方法返回一个 utf-8 字符串(即 getvalue() 的结果) StringIO() 为保存转储数据而创建的实例)并且在将其附加到字符串之前必须将其转换为 utf-8

# coding: utf-8

import codecs
import ruamel.yaml as yaml

file_name = r'toto.txt'

text = u'héhéhé, hûhûhû'

textDict = {"data": text}

with open(file_name, 'w') as fp:
    yaml.dump(textDict, stream=fp, allow_unicode=True)

print('yaml dump dict 1   : ' + open(file_name).read()),

f = codecs.open(file_name,"w",encoding="utf-8")
f.write('yaml dump dict 2   : ' + yaml.dump(textDict, allow_unicode=True).decode('utf-8'))
f.close()
print(open(file_name).read())

输出:

yaml dump dict 1    : {data: 'héhéhé, hûhûhû'}
yaml dump dict 2    : {data: 'héhéhé, hûhûhû'}

我用我的增强版 PyYAML ( ruamel.yaml ) 对此进行了测试,但这在 PyYAML 本身中应该是一样的。

关于python - PyYaml - 转储带有特殊字符(即重音符号)的 unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29342757/

相关文章:

将 'None' 字符串转换为 None 的 Pythonic 方式

Python 我如何使列表追加/扩展更快?

java - 带有 unicode 换行符的注释语句

c++ - wchar_t 究竟能代表什么?

python - 与 Python 中的 unicode 混淆

Azure Pipelines (yaml) 使用条件设置新变量

yaml - CloudFormation YAML 状态机 : INVALID_JSON_DESCRIPTION for unrecognized token

python - 使用 setuptools 时是否有任何理由列出标准库依赖项?

python 无法访问 suds 方法

python - 取第三轴具有最大值的轴