PyYaml - 使用特殊字符(即重音符号)转储unicode

Han*_*uhn 11 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()
Run Code Online (Sandbox Code Playgroud)

书面文件包含:

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"}
Run Code Online (Sandbox Code Playgroud)

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

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

我想转储包含带重音的文本,而不是unicode代码.那可能吗 ?

Ant*_*hon 15

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

# coding: utf-8

import codecs
import raumel.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()),
Run Code Online (Sandbox Code Playgroud)

输出:

yaml dump dict 1    : {data: 'héhéhé, hûhûhû'}
yaml dump dict 2    : {data: 'héhéhé, hûhûhû'}
Run Code Online (Sandbox Code Playgroud)

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


fra*_*lau 7

更新(2020)

\n

如今,PyYaml可以轻松地使用 Python 3 处理 unicode,但这需要allow_unicode=True参数:

\n
import yaml\nd = {\'a\': \'h\xc3\xa9h\xc3\xa9h\xc3\xa9\', \'b\': \'h\xc3\xbch\xc3\xbch\xc3\xbc\'}\nyaml_code = yaml.dump(d, allow_unicode=True, sort_keys=False)\nprint(yaml_code)\n
Run Code Online (Sandbox Code Playgroud)\n

将导致:

\n
a: h\xc3\xa9h\xc3\xa9h\xc3\xa9\nb: h\xc3\xbch\xc3\xbch\xc3\xbc\n
Run Code Online (Sandbox Code Playgroud)\n

注意sortkeys=False自 Python 3.6 起应使用该参数,以保持字典的键不变。PyYaml 传统上对键进行排序,因为 Python 字典没有明确的顺序。尽管从 Python 3.6 开始字典键就已经排序了;从3.7 开始,PyYaml 开始默认对键进行排序。

\n