如何让Python Yaml库以人性化的方式保存?

2024-01-30

这是我得到的 Python 代码:

d = {'ToGoFirst': 'aaa', 'Second': 'bbb', 'Pagargaph':
'''Lorem ipsum dolor sit amet, 
consectetur adipiscing elit, 
sed do eiusmod tempor incididunt 
ut labore et dolore magna aliqua.''',  
'Integer': 25}
with open('d.yaml', 'w') as f:
    yaml.safe_dump(d, f, default_flow_style=False)

我不断得到什么:

Integer: 25
Pagargaph: "Lorem ipsum dolor sit amet, \nconsectetur adipiscing elit, \nsed do eiusmod\
  \ tempor incididunt \nut labore et dolore magna aliqua."
Second: bbb
ToGoFirst: aaa

我如何改变它以产生:

ToGoFirst: aaa
Second: bbb
Pagargaph: 
  Lorem ipsum dolor sit amet, 
  consectetur adipiscing elit, 
  sed do eiusmod tempor incididunt 
  ut labore et dolore magna aliqua.
Integer: 25

换句话说,我想:

  1. 避免在输出中使用引号和转义字符,以便非技术用户可以读取和编辑这些配置文件。

  2. 理想情况下保留参数的顺序。

这是为了能够加载 YAML 文件,添加更多参数,并且仍然能够以人类友好的格式保存它。


您的输出的值中没有换行符Pagargaph,为此你需要有一个块式文字标量 http://yaml.org/spec/1.2/spec.html#id2795688(破折号会修剪最后的换行符,通常在加载此类标量时会得到):

Pagargaph: |-
  Lorem ipsum dolor sit amet, 
  consectetur adipiscing elit, 
  sed do eiusmod tempor incididunt 
  ut labore et dolore magna aliqua.

你应该使用ruamel.yaml https://yaml.readthedocs.io/en/latest/(免责声明:我是该包的作者),它是专门为支持这种往返而开发的。为了得到你想做的事情,例如:

import sys
import ruamel.yaml
from ruamel.yaml.scalarstring import PreservedScalarString as L

yaml_str = """\
ToGoFirst: aaa
Second: 'bbb'  # insert after this one
Integer: 25
"""

yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True
d = yaml.load(yaml_str)
# yaml.indent(mapping=4, sequence=4, offset=2)
try:
    before_integer = [k for k in d].index('Integer')
except ValueError:
    before_integer = len(d)
d.insert(before_integer, 'Pagargaph', L('''Lorem ipsum dolor sit amet, 
consectetur adipiscing elit, 
sed do eiusmod tempor incididunt 
ut labore et dolore magna aliqua.'''))  
d.insert(before_integer, 'Something', 'extra', comment='with a comment')
yaml.dump(d, sys.stdout)

导致:

ToGoFirst: aaa
Second: 'bbb'  # insert after this one
Something: extra # with a comment
Pagargaph: |-
  Lorem ipsum dolor sit amet, 
  consectetur adipiscing elit, 
  sed do eiusmod tempor incididunt 
  ut labore et dolore magna aliqua.
Integer: 25

请注意:

  • 该顺序在 ruamel.yaml 支持的任何版本的 Python 中都会保留(2.7、3.4+)
  • 评论已保留
  • 我添加的引号bbb仅当您指定时才保留yaml.preserve_quotes = True
  • 因为我们在位置 2 插入两次,所以后者将前者撞到了位置 3。

您的用户必须遵守一些纪律,才能编辑 YAML 文件而不破坏它。他们还应该知道一些注意事项,例如普通(未引用的)标量不能以某些特殊字符开头或包含特殊字符序列(:其次是空间,#前面有空格)

为了帮助防止用户犯编辑错误,您可以尝试在 YAML 文档的开头添加以下注释:

# please read the first few "rules" of How_to_edit at the bottom of this file

最后:

How_to_edit: |
 Editing a YAML document is easy, but there are some rules to keep you from 
 accidently invoking its hidden powers. Of the following you need at least 
 read and apply the ones up to the divider separating the important from less 
 important rules. The less important ones are interesting, but you probably 
 won't need to know them.
 1) Entries in this file consist of a scalar key (before the ':') and a scalar 
    value (normally after the ':', but read rule 3). 
 2) Scalars do NOT need quotes (single: ', or double: ") around them, unless 
    you have a special character or characters combinations at the beginning 
    ('%', '*', '&', '{', '[', '- ') or in the middle  (': ', ' #) of the  scalar.
    If you add quotes use a single quote before and after the scalar . If 
    these are superfluous the program can remove them. So when in doubt just 
    add them.
 3) A key followed by ': |' introduces a multiline scalar. These instructions
    are in a multiline scalar. Such a scalar starts on the next line after ': |'.
    The lines need to be indented, until the end of the scalar and these 
    indentation spaces are not part of the scalar. 
    The newlines in a multiline sclar are hard (i.e. preserved, and not 
    substituted with spaces).
    If you see `: |-` that means the scalar is loaded with the trailing newline 
    stripped.
 4) Anything after a space followed by a hash (' #') is a comment, when not 
    within quotes or in a multiline string.
 --- end of the important rules ---
 5) Within single quoted scalars you can have a single quote by doubling it: 
       rule 4: 'you probably don''t ever need that'
    This is called escaping the single quote. You can double quote scalars, but 
    the rules for escaping are much more difficult, so don't try that at home.
 6) The scalars consisting solely of "True" and "False" (also all-caps and 
    all-lowercase) are loaded as booleans when unquoted, and as strings when 
    quoted. 
 7) Scalars consisting solely of number characters (0-9) are loaded as numbers.
    If there is a non-number they are usually loaded as strings, but scalars 
    starting with '0x' and '0o' and for the rest have only number characters,
    are special and need quotes if not intended as (hexadecimal resp. octal) 
    numbers.

如果包含上述内容,您可能不想在往返时保留引号。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何让Python Yaml库以人性化的方式保存? 的相关文章

随机推荐

  • 以编程方式将 YouTube 视频添加到墙贴

    如何在 Facebook 墙中嵌入 YouTube 视频 我尝试使用 源 成员传递视频网址 但没有成功 在检查手动发布的提要的 json 后 我发现 FB 的服务器代码进行了一些处理来实现这一点 提要向我展示了这一点 id 10000146
  • 有没有纯Python的Lucene?

    红宝石人有Ferret https github com dbalmain ferret 有人知道 Python 有类似的计划吗 我们目前使用 PyLucene 但我想研究转向纯 Python 搜索 Whoosh http pypi pyt
  • 将哈希中的一个匹配值替换为另一个值

    我有一个哈希数组 arr key1 gt one key2 gt two key3 gt three key1 gt four key2 gt five key3 gt six key1 gt seven key2 gt eight key
  • 在 pandas 中将月份从数字重命名为名称

    我有以下数据框 High Low Open Close Volume Adj Close year pct day month day 1 1 NaN NaN NaN NaN NaN NaN 2010 0 0 000000 2 7869 8
  • 如何获取 UI 元素的屏幕位置?

    我正在尝试获取 UI 元素的全局位置 我尝试了很多不同的方法来获得这个职位 但似乎都不起作用 问题出在锚点上 因为我移动它们而不是 UI 元素位置本身 出于分辨率目的 检查器中显示的 UI 位置始终为 0 0 0 我还尝试让anchored
  • 为什么精挑细选会导致仓库不稳定? [关闭]

    Closed 这个问题需要细节或清晰度 help closed questions 目前不接受答案 我不是开发人员 在我们的一个项目中 由于很多门票需要时间才能完成 因此我们一直在挑选我们的提交 现在我们必须经常这样做 一位开发人员告诉我
  • 为什么我的 jquery UI 日期选择器没有默认为英语

    我基本上复制了代码从这里 http jqueryui com demos datepicker 但是当我测试我的网站时我看到了这个 替代文本 http img148 imageshack us img148 8167 datepicker
  • 是否可以在 Action Script 3 中动态创建用户定义类的实例?

    我有一个工厂 其中 Action Script 遵循 xml 并从中构建 DisplayObject 层次结构 这意味着脚本事先并不知道它将在 xml 中遇到哪些元素 因此也不知道它将需要哪些用户定义的工厂类 我知道可以做这样的事情 var
  • Web 部署 - 使用相对路径进行本地文件系统部署

    我想使用 Web 部署来运行自定义部署设置 因为我希望在许多不同的环境 团队成员本地计算机 4 个不同的构建服务器 上运行时都能正常工作 所以我想部署到相对的本地路径 我想做的是 部署到本地relative path 让构建后的步骤做神奇的
  • 扭曲中的持久连接

    我是 Twisted 的新手 有一个问题 如何在 Twisted 中组织持久连接 我有一个队列 每秒都会检查它 如果有一些 发送给客户端 我找不到比每秒调用 dataReceived 更好的方法了 下面是协议实现的代码 class Sync
  • 同构镜片

    我对 van Laarhoven 的一个小例子感兴趣同构透镜 http twanvl nl blog haskell isomorphism lenses 应用于像这样的数据类型data BValue BValue Float Float
  • android:smoothScrollToPosition()无法正常工作

    在将元素添加到与列表视图关联的数组适配器后 我试图平滑地滚动到列表的最后一个元素 问题是它只是滚动到随机位置 arrayadapter add item DOES NOT WORK CORRECTLY listview smoothScro
  • 如何在tensorflow keras中使用CRF?

    代码是这样的 import tensorflow as tf from keras contrib layers import CRF from tensorflow import keras def create model max se
  • 在Python中从url下载csv.gz文件

    我在从网址下载 csv gz 文件时遇到问题 我在下载 tar gz 文件时没有问题 对于 csv gz 文件 我可以提取 gz 文件并读取我的 csv 文件 如果我可以使用 URL 而不是事先拥有 csv 1 0 csv gz 那就很方便
  • 为 UIBarButtonItem 设置图像 - 图像拉伸

    当我尝试使用 UIBarButtonItem 的 initWithImage 来初始化导航栏自定义图像时 它会被冲破并拉伸到黑色导航栏上 这就是我创建它的方式 UIBarButtonItem button UIBarButtonItem a
  • 警告:为 foreach() 提供的参数无效

    results mysql query select from classpics foreach results as uno echo td valign middle align center a class neutral href
  • Linux中使用的offsetof

    我正在研究如何在给定结构中找到特定变量的偏移量 我尝试了以下程序 struct info char a int b char c int d struct info myinfo int main int argc char argv st
  • 缓存URL内容

    我有一个非常简单的用例 当远程端的内容发生变化时 例如 当 上次修改 发生变化时 通过正确和自动重新加载来缓存 URL 的内容 我怎样才能在Java中做到这一点 注意 我的类路径上有 spring guava 和 commons lang3
  • 从 ABC 和 django.db.models.Model 继承会引发元类异常

    我正在尝试使用Python 3实现一个Django数据模型类 它也是一个接口类 我这样做的原因是 我正在为我的同事编写一个基类 并且需要他全部实现三个方法他从我的课程中派生出来的 我试图为他提供一种简化的方式来使用我设计的系统的功能 但是
  • 如何让Python Yaml库以人性化的方式保存?

    这是我得到的 Python 代码 d ToGoFirst aaa Second bbb Pagargaph Lorem ipsum dolor sit amet consectetur adipiscing elit sed do eius