pyyaml:不带标签的转储
我有
>>> import yaml
>>> yaml.dump(u'abc')
"!!python/unicode 'abc'\n"
但我想要
>>> import yaml
>>> yaml.dump(u'abc', magic='something')
'abc\n'
什么神奇参数强制不加标签?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用
safe_dump
代替dump
。请记住,它将无法表示任意 Python 对象。此外,当您加载
YAML 时,您将获得一个str
对象,而不是unicode
。You can use
safe_dump
instead ofdump
. Just keep in mind that it won't be able to represent arbitrary Python objects then. Also, when youload
the YAML, you will get astr
object instead ofunicode
.怎么样:
这似乎使转储 unicode 对象的工作方式与转储 str 对象对我来说相同(Python 2.6)。
How about this:
This seems to make dumping unicode objects work the same as dumping str objects for me (Python 2.6).
您需要一个新的转储器类,它可以完成标准转储器类所做的所有事情,但覆盖 str 和 unicode 的表示。
这导致了
当然,我仍然不知道如何保持这个漂亮。
它破坏了后来的 yaml.load()
You need a new dumper class that does everything the standard Dumper class does but overrides the representers for str and unicode.
Which leads to
Granted, I'm still stumped on how to keep this pretty.
And it breaks a later yaml.load()
除了 interjay 的出色答案之外,如果您注意文件编码,则可以重新加载您的 unicode。
test2.yaml 编辑器中的内容:
{key: "abc\xE7\uD83D\uDD11"}
打印输出:
('data2:', {'key ': u'abc\xe7\U0001f511'}, 'type(data.key):',)
abcç
little addition to interjay's excellent answer, you can keep your unicode on a reload if you take care of your file encodings.
test2.yaml contents in my editor:
{key: "abc\xE7\uD83D\uDD11"}
print outputs:
('data2:', {'key': u'abc\xe7\U0001f511'}, 'type(data.key):', <type 'unicode'>)
abcç????
Plus, after reading http://nedbatchelder.com/blog/201302/war_is_peace.html I am pretty sure that safe_load/safe_dump is where I want to be anyway.
我刚刚开始使用 Python 和 YAML,但这可能也有帮助。只需比较输出:
I've just started with Python and YAML, but probably this may also help. Just compare outputs: