zoukankan      html  css  js  c++  java
  • YAML 在Python中的应用

        编程免不了要写配置文件,怎么写配置也是一门学问。

        YAML 是专门用来写配置文件的语言,非常简洁和强大,远比 JSON 格式方便。

        YAML在python语言中有PyYAML安装包,下载地址:https://pypi.python.org/pypi/PyYAML

      一、简介

        YAML 语言(发音 /ˈjæməl/ )的设计目标,就是方便人类读写。它实质上是一种通用的数据串行化格式。

        它的基本语法规则如下:

        1、大小写敏感

        2、使用缩进表示层级关系

        3、缩进时不允许使用Tab键,只允许使用空格。

        4、缩进的空格数目不重要,只要相同层级的元素左侧对齐即可

        5、# 表示注释,从这个字符一直到行尾,都会被解析器忽略,这个和python的注释一样

        YAML 支持的数据结构有三种:

        1、对象:键值对的集合,又称为映射(mapping)/ 哈希(hashes) / 字典(dictionary)

        2、数组:一组按次序排列的值,又称为序列(sequence) / 列表(list)

        3、纯量(scalars):单个的、不可再分的值。字符串、布尔值、整数、浮点数、Null、时间、日期

      二、字符串

        

    #######################################字符串##############################################
    #1、字符串默认不使用引号表示
    str1: 这是一个字符串
    
    #2、如果字符串之中包含空格或特殊字符,需要放在引号之中。
    str2: '内容: *字符串'
    
    #3、单引号和双引号都可以使用,双引号不会对特殊字符转义。
    str3: '内容
    字符串'
    str4: "content
     string"
    
    #4、单引号之中如果还有单引号,必须连续使用两个单引号转义。
    s3: 'labor''s day'
    
    #5、字符串可以写成多行,从第二行开始,必须有一个单空格缩进。换行符会被转为空格
    strline: 这是一段
      多行
      字符串
      
    #6、多行字符串可以使用|保留换行符,也可以使用>折叠换行
    this: |
      Foo
      Bar
    that: >
      Foo
      Bar
      
    #7、+表示保留文字块末尾的换行,-表示删除字符串末尾的换行。
    s4: |
      Foo4
    s5: |+
      Foo5
    s6: |-
      Foo6
    s7: |
      Foo7

      

      三、对象

    ###################################对象####################
    #1、对象的一组键值对,使用冒号结构表示。
    animal: pets  #{'animal': 'pets'}
    #
    ##2、Yaml 也允许另一种写法,将所有键值对写成一个行内对象
    dict1: { name: Steve, foo: bar } #{'dict1': {'foo': 'bar', 'name': 'Steve'}}

      四、数组

    ####################################数组###################
    
    # 1、数组可以采用行内表示法。
    animal: [Cat, Dog]
    
    #{'animal': ['Cat', 'Dog']}
    
    #2、一组连词线开头的行,构成一个数组。
    animal1:
     - Cat
     - Dog
     - Goldfish
    
    # {'animal1': ['Cat', 'Dog', 'Goldfish']}

      五、复合结构

    ############################复合结构##########################
    #对象和数组可以结合使用,形成复合结构
    
    languages:
     - Ruby
     - Perl
     - Python
    websites:
     YAML: yaml.org
     Ruby: ruby-lang.org
     Python: python.org
     Perl: use.perl.org
    #{'languages': ['Ruby', 'Perl', 'Python'], 'websites': {'Python': 'python.org', 'YAML': 'yaml.org', 'Ruby': 'ruby-lang.org', 'Perl': 'use.perl.org'}}
    
    db:
        host: xxx
        port: 3306
        user: weibospider
        password: xxx
        db_name: weibo
        db_type: mysql
    
    #{'db': {'host': 'xxx', 'db_name': 'weibo', 'user': 'weibospider', 'db_type': 'mysql', 'password': 'xxx', 'port': 3306}}
    

      六、纯量

    ##########################纯量#############################
    #1、数值直接以字面量的形式表示
    number: 12.30 #{'number': 12.3}
    
    #2、布尔值用true和false表示
    isSet: true #{'isSet': True}
    isSet1: false #{'isSet1': False}
    
    3、null用~表示
    parent: ~   #{'parent': None}
    
    #4、时间采用 ISO8601 格式。
    time1: 2001-12-14t21:59:43.10-05:00  #{'time1': datetime.datetime(2001, 12, 15, 2, 59, 43, 100000)}
    
    ##5、日期采用复合 iso8601 格式的年、月、日表示。
    date: 2017-07-31  #{'date': datetime.date(2017, 7, 31)}
    
    #6、YAML 允许使用两个感叹号,强制转换数据类型。
    int_to_str: !!str 123  #{'bool_to_str': 'true'}
    bool_to_str: !!str true #{'bool_to_str': 'true'}

      七、YAML应用

        这里主要是记录一下YAML在Python语言中的应用。类比于json库,yaml库与其有惊人的相似之处。一个load方法,一个dump方法。顾名知义,也比较的好理解。

    # coding:utf-8
    import os
    
    import sys
    reload(sys)
    sys.setdefaultencoding('utf8')
    
    from yaml import load
    config_path = os.path.join(os.path.dirname(__file__), 'tt.yaml')
    
    
    with open(config_path,'rb') as f:
        cont = f.read()
    
    cf = load(cont)
    
    print cf.get('db')
    # 输出:{'host': 'xxx', 'db_name': 'weibo', 'user': 'weibospider', 'db_type': 'mysql', 'password': 'xxx', 'port': 3306}
    print '------------------'
    
    print cf
    
    # 输出:
    '''
    {'
        dict1': {'foo': 'bar', 'name': 'Steve'},
        'animal1': ['Cat', 'Dog', 'Goldfish'],
        'parent': None,
        'bool_to_str': 'true',
        'db': {'host': 'xxx', 'db_name': 'weibo', 'user': 'weibospider', 'db_type': 'mysql', 'password': 'xxx', 'port': 3306},
        'number': 12.3,
        'websites': {'Python': 'python.org', 'YAML': 'yaml.org', 'Ruby': 'ruby-lang.org', 'Perl': 'use.perl.org'}, 
        'time1': datetime.datetime(2001, 12, 15, 2, 59, 43, 100000), 
        'languages': ['Ruby', 'Perl', 'Python'],
        'animal': ['Cat', 'Dog'],
        'date': datetime.date(2017, 7, 31),
        'int_to_str': '123', 
        'isSet': True, 
        'isSet1': False}
    '''

      参考文档:http://www.ruanyifeng.com/blog/2016/07/yaml.html

  • 相关阅读:
    leetcode33. Search in Rotated Sorted Array
    pycharm 设置sublime text3 monokai主题
    django class Meta
    leetcode30, Substring With Concatenation Of All Words
    Sublime text3修改tab键为缩进为四个空格,
    sublime text3 python打开图像的问题
    安装上imesupport输入法依然不跟随的解决办法,
    sublime text3 的插件冲突弃用问题,
    sublime text3 BracketHighlighter括号匹配的设置
    windows 下wget的使用
  • 原文地址:https://www.cnblogs.com/shaosks/p/7344771.html
Copyright © 2011-2022 走看看