gpt4 book ai didi

python - Python 中是否有任何支持将长字符串转储为 block 文字或折叠 block 的 yaml 库?

转载 作者:IT老高 更新时间:2023-10-28 20:51:17 39 4
gpt4 key购买 nike

我希望能够转储包含长字符串的字典,我希望在 block 样式中具有可读性。例如:

foo: |
this is a
block literal
bar: >
this is a
folded block

PyYAML 支持加载具有这种样式的文档,但我似乎找不到以这种方式转储文档的方法。我错过了什么吗?

最佳答案

import yaml

class folded_unicode(unicode): pass
class literal_unicode(unicode): pass

def folded_unicode_representer(dumper, data):
return dumper.represent_scalar(u'tag:yaml.org,2002:str', data, style='>')
def literal_unicode_representer(dumper, data):
return dumper.represent_scalar(u'tag:yaml.org,2002:str', data, style='|')

yaml.add_representer(folded_unicode, folded_unicode_representer)
yaml.add_representer(literal_unicode, literal_unicode_representer)

data = {
'literal':literal_unicode(
u'by hjw ___\n'
' __ /.-.\\\n'
' / )_____________\\\\ Y\n'
' /_ /=== == === === =\\ _\\_\n'
'( /)=== == === === == Y \\\n'
' `-------------------( o )\n'
' \\___/\n'),
'folded': folded_unicode(
u'It removes all ordinary curses from all equipped items. '
'Heavy or permanent curses are unaffected.\n')}

print yaml.dump(data)

结果:

folded: >
It removes all ordinary curses from all equipped items. Heavy or permanent curses
are unaffected.
literal: |
by hjw ___
__ /.-.\
/ )_____________\\ Y
/_ /=== == === === =\ _\_
( /)=== == === === == Y \
`-------------------( o )
\___/

为了完整起见,还应该有 str 实现,但我会偷懒:-)

关于python - Python 中是否有任何支持将长字符串转储为 block 文字或折叠 block 的 yaml 库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6432605/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com