基于python脚本的yaml订单保存

2024-10-01 22:29:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写python脚本,它可以使我的yaml工作自动化。我将从不同的csv文件创建一个yaml结构。但目前我正试图通过例子来理解yaml结构。我在看一些yaml教程和示例,遇到了一个需要正确解决的问题

对于上面的结构,我的python代码如下

import sys
import yaml
from collections import OrderedDict

d = {'version': '22-07-2017', 'description': 'energie balance',
     'info': {
         'principalInvestigator': 'Kalthoff',
         'personInCharge': 'Scheer'
     },
     'dataSources': 'null',
     'devices': {
       'type': 'HMP',
       'info': {
           'description': 'temperature and humidity sensor',
           'company': 'Vaisala',
           'model': 'HMP35A',
           },
       'measures': {
           'quantity': 'T',
           'annotations': 'air',
           'sensors': {
               'number': '001',
               'sources': {
                   'id': 'null',
                   'frequency': '0.1',
                   'aggregation': 'AVG',
                   'field': 'null'
                   }
               }

           }
       }
     }
with open('/home/ali/Desktop/yaml-conf-task/result.yml', 'w') as yaml_file:
yaml.dump(d, yaml_file,  default_flow_style=False)

但当我打开yaml文件时,它会给我未排序的数据。我收到这个

^{pr2}$

而不是得到这个

version: 21-07-2017
description: energie balance
info:
  principalInvestigator: rob
  personInCharge: rio
dataSources: null
devices:
  - type: TMP
    info:
      description: temperature and humidity sensor
      company: Vio
      model: 35A
    measures:
      - quantity: T
        annotation: air
        sensors:
          - number: 001
            sources:
              - id: null
                frequency: 1
                aggregation: AVG
                field: null

如果有人建议我如何维持秩序,我将不胜感激。我查看了堆栈溢出,但无法解决问题。在


Tags: importinfoyamlversiontypedescription结构null
1条回答
网友
1楼 · 发布于 2024-10-01 22:29:35

首先,从技术上讲,YAML是JSON的超集,因此,根据规范,不能保证映射集的顺序。因此,您要实现的并不是您能够在任何地方复制的东西,除非您控制了完整的数据流,否则您可能会遇到问题。在

另外,正如我在评论中所说的,Python自己的dict通常不是保序的,但是Python有collections.OrderedDict,您可以重新声明您的结构以保持顺序为:

from collections import OrderedDict

d = OrderedDict([('version', '22-07-2017'), ('description', 'energie balance'),
                 ('info', OrderedDict([
                     ('principalInvestigator', 'Kalthoff'),
                     ('personInCharge', 'Scheer')
                 ])),
                 ('dataSources', 'null'),
                 ('devices', OrderedDict([
                     ('type', 'HMP'),
                     ('info', OrderedDict([
                         ('description', 'temperature and humidity sensor'),
                         ('company', 'Vaisala'),
                         ('model', 'HMP35A')
                     ])),
                     ('measures', OrderedDict([
                         ('quantity', 'T'),
                         ('annotations', 'air'),
                         ('sensors', OrderedDict([
                             ('number', '001'),
                             ('sources', OrderedDict([
                                 ('id', 'null'),
                                 ('frequency', '0.1'),
                                 ('aggregation', 'AVG'),
                                 ('field', 'null')
                             ]))
                         ]))
                     ]))
                 ]))
                 ])

是的,这比一个干净的dict结构有点恶心,因为您必须使用嵌套的列表/元组来保持顺序,但是一旦您习惯了它,就不那么困难了—您只需要将所有的dict声明替换为OrderedDict([]),并将所有key: value声明替换为{}。在

但这只是等式的一部分-一旦你有了一个保持其顺序的dict-like结构,你的YAML序列化程序也应该知道它。如果您只是通过一个通用的YAML序列化程序(假设是^{})转储上述结构,您将得到:

^{pr2}$

当然,它保持了顺序,但它导出了实际的内部collections.OrderedDict结构,允许您将其加载回相同的结构中,这不是您想要的。相反,您需要告诉它将您的OrderedDict视为常规映射集,因此:

import yaml

def ordered_dict_representer(self, value):  # can be a lambda if that's what you prefer
    return self.represent_mapping('tag:yaml.org,2002:map', value.items())
yaml.add_representer(OrderedDict, ordered_dict_representer)

现在,如果将其导出为:

with open('/home/ali/Desktop/yaml-conf-task/result.yml', 'w') as yaml_file:
    yaml.dump(d, yaml_file,  default_flow_style=False)

您将获得:

version: 22-07-2017
description: energie balance
info:
  principalInvestigator: Kalthoff
  personInCharge: Scheer
dataSources: 'null'
devices:
  type: HMP
  info:
    description: temperature and humidity sensor
    company: Vaisala
    model: HMP35A
  measures:
    quantity: T
    annotations: air
    sensors:
      number: '001'
      sources:
        id: 'null'
        frequency: '0.1'
        aggregation: AVG
        field: 'null'

相关问题 更多 >

    热门问题