Саш*_*ных 5 yaml pyyaml ruamel.yaml
我找不到如何使用注释对 YAML 文件进行排序。
\n\n我能找到的解决方案:
\n\n删除评论,
\n\n或者
不要在右行之后保存注释。
我有一个文件SashaSort.yaml:
sasha: great\n# Kristina comment\nkristina: legendary\nkatya: \'\xd0\x92\xd0\xb5\xd1\x87\xd0\xbd\xd0\xb0\xd1\x8f \xd0\xbf\xd0\xb0\xd0\xbc\xd1\x8f\xd1\x82\xd1\x8c\'\nRun Code Online (Sandbox Code Playgroud)\n\nkatya: \'\xd0\x92\xd0\xb5\xd1\x87\xd0\xbd\xd0\xb0\xd1\x8f \xd0\xbf\xd0\xb0\xd0\xbc\xd1\x8f\xd1\x82\xd1\x8c\'\n# Kristina comment\nkristina: legendary\nsasha: great\nRun Code Online (Sandbox Code Playgroud)\n\n(必须保存非 ASCII 符号。)
\n\n如果我使用i18n_yaml_sorter,我会得到输出:
\n\nkatya: \'\xd0\x92\xd0\xb5\xd1\x87\xd0\xbd\xd0\xb0\xd1\x8f \xd0\xbf\xd0\xb0\xd0\xbc\xd1\x8f\xd1\x82\xd1\x8c\'\nkristina: legendary\nsasha: great\n# Kristina comment\nRun Code Online (Sandbox Code Playgroud)\n\n评论保存不在上方kristina: legendary。
写问题毫无用处,因为 i18n_yaml_sorter 中的最后一次提交是在 2011。
我找不到如何对ruamel.yaml文档中的 YAML 进行排序,
ruamel.yaml.cmd。PyYAML不支持注释。
\nruamel.yaml确实支持,但是需要一些排序的努力。关于引用 ruamel.yaml当前行或上面行的注释的要点:
- one # comment to the current line\n# comment to the line above (one)\n- two\nRun Code Online (Sandbox Code Playgroud)\n因此,您应该重新组织解析器结果(并学习保留注释的一些技巧)。我创建了一个模块comments_sort.py来简化这个过程。您可以查看演示脚本。至于请求的示例,它将如下所示:
import sys\n\nimport ruamel.yaml\nfrom comments_sort import map_sort_before\n\nyaml = ruamel.yaml.YAML()\n\nyaml_str = """\\\nsasha: great\n# Kristina comment\nkristina: legendary\nkatya: \'\xd0\x92\xd0\xb5\xd1\x87\xd0\xbd\xd0\xb0\xd1\x8f \xd0\xbf\xd0\xb0\xd0\xbc\xd1\x8f\xd1\x82\xd1\x8c\'\n"""\n\nobj = yaml.load(yaml_str)\nsorted_keys = sorted(\n list(obj.keys()),\n key=lambda x: x,\n)\nobj_sorted = map_sort_before(obj, sorted_keys)\nyaml.dump(obj_sorted, sys.stdout)\nRun Code Online (Sandbox Code Playgroud)\n输出是:
\nkatya: \xd0\x92\xd0\xb5\xd1\x87\xd0\xbd\xd0\xb0\xd1\x8f \xd0\xbf\xd0\xb0\xd0\xbc\xd1\x8f\xd1\x82\xd1\x8c\n# Kristina comment\nkristina: legendary\nsasha: great\nRun Code Online (Sandbox Code Playgroud)\n对于反向排序:
\nkatya: \xd0\x92\xd0\xb5\xd1\x87\xd0\xbd\xd0\xb0\xd1\x8f \xd0\xbf\xd0\xb0\xd0\xbc\xd1\x8f\xd1\x82\xd1\x8c\n# Kristina comment\nkristina: legendary\nsasha: great\nRun Code Online (Sandbox Code Playgroud)\n输出是:
\nsasha: great\n# Kristina comment\nkristina: legendary\nkatya: \xd0\x92\xd0\xb5\xd1\x87\xd0\xbd\xd0\xb0\xd1\x8f \xd0\xbf\xd0\xb0\xd0\xbc\xd1\x8f\xd1\x82\xd1\x8c\nRun Code Online (Sandbox Code Playgroud)\n