#简单介绍==============================================================

YAML使用寄主语言的数据类型,这在多种语言中流传的时候可能会引起兼容性的问题。

YAML语法规则:

http://www.ibm.com/developerworks/cn/xml/x-cn-yamlintro/

http://www.yaml.org/

事例:

name: Tom Smith
age: 37
spouse:
name: Jane Smith
age: 25
children:
- name: Jimmy Smith
age: 15
- name1: Jenny Smith
age1: 12

使用python的yaml库PyYAML。http://pyyaml.org/

#在python中的应用========================================================

安装到python lib下后就可以正常使用了。

主要介绍yaml在python中如何读写。

1、读取单个yaml文件

yaml.load()方法

使用举例:

 #加载yaml
import yaml #读取文件
f = open('test.yaml') #导入
x = yaml.load(f) print x

会得到结果:

 {'age': 37, 'spouse': {'age': 25, 'name': 'Jane Smith'}, 'name': 'Tom Smith', 'children': [{'age': 15, 'name': 'Jimmy Smith'}, {'age1': 12, 'name1': 'Jenny Smith'}]}

在读取yaml文件时,对文件格式的要求极其的严格。有时候没有报错,却读不出任何内容。

文件的格式错误也是常有的事,注意:

yaml.load accepts a byte string, a Unicode string, an open binary file object, or an open text file object. A byte string or a file must be encoded with utf-8utf-16-be or utf-16-le encoding. yaml.load detects the encoding by checking the BOM (byte order mark) sequence at the beginning of the string/file. If no BOM is present, theutf-8 encoding is assumed.

yaml.load可接收一个byte字符串,unicode字符串,打开的二进制文件或文本文件对象。字节字符串和文件必须是utf-8,utf-16-be或utf-16-le编码的.yaml.load通过检查字符串/文件开始的BOM(字节序标记)来确认编码。如果没有BOM,就默认为utf-8。

2、读取多个yaml

yaml.load_all()

如果string或文件包含几块yaml文档,你可以使用yaml.load_all来解析全部的文档。

 yaml.load(stream, Loader=<class 'yaml.loader.Loader'>)
Parse the first YAML document in a stream #只解析第一个
and produce the corresponding Python object. yaml.load_all(stream, Loader=<class 'yaml.loader.Loader'>)
Parse all YAML documents in a stream
and produce corresponding Python objects.

注意,yaml.load_all 会生成一个迭代器,你要做的就是for 读出来

 documents = """
name: The Set of Gauntlets 'Pauraegen'
description: >
A set of handgear with sparks that crackle
across its knuckleguards.
---
name: The Set of Gauntlets 'Paurnen'
description: >
A set of gauntlets that gives off a foul,
acrid odour yet remains untarnished.
---
name: The Set of Gauntlets 'Paurnimmen'
description: >
A set of handgear, freezing with unnatural cold.
""" for data in yaml.load_all(documents):
print data #{'description': 'A set of handgear with sparks that crackle across its #knuckleguards.\n',
#'name': "The Set of Gauntlets 'Pauraegen'"}
#{'description': 'A set of gauntlets that gives off a foul, acrid odour #yet remains untarnished.\n',
#'name': "The Set of Gauntlets 'Paurnen'"}
#{'description': 'A set of handgear, freezing with unnatural cold.\n',
#'name': "The Set of Gauntlets 'Paurnimmen'"}

safe_load描述

PyYAML allows you to construct a Python object of any type.

Even instances of Python classes can be constructed using the !!python/object tag.

PyYaml允许你构建任何类型的python对象,甚至是python类实例,只需要借助一下yaml标签!!python/object。

这个以后再说,非常有用的东西。

Note that the ability to construct an arbitrary Python object may be dangerous if you receive a YAML document from an untrusted source such as Internet. The function yaml.safe_load limits this ability to simple Python objects like integers or lists.

需要注意的是随意在yaml里构建python对象是有一定危险的,尤其是接收到一个未知的yaml文档。yaml.safe_load可以限制这个能力,就使用些简单的对象吧。

3、写yaml文件

yaml.dump 将一个python对象生成为yaml文档,与yaml.load搭配使用。

 dump(data, stream=None, Dumper=<class 'yaml.dumper.Dumper'>, **kwds)

     Serialize a Python object into a YAML stream.
If stream is None, return the produced string instead.
#很好,如果缺省数据流为空的话,就会给你返回个字符串作为yaml文档

应用事例:

 aproject = {'name': 'Silenthand Olleander',
'race': 'Human',
'traits': ['ONE_HAND', 'ONE_EYE']
} print yaml.dump(aproject) #返回
#name: Silenthand Olleander
#race: Human
#traits: [ONE_HAND, ONE_EYE]

yaml.dump accepts the second optional argument, which must be an open text or binary file. In this case,yaml.dump will write the produced YAML document into the file. Otherwise, yaml.dump returns the produced document.

解释上面那句话的:yaml.dump接收的第二个参数一定要是一个打开的文本文件或二进制文件,yaml.dump会把生成的yaml文档写到文件里。否则,yaml.dump会返回生成的文档。

4、写多个yaml内容,yaml.dump_all函数

If you need to dump several YAML documents to a single stream, use the function yaml.dump_all.yaml.dump_all accepts a list or a generator producing

Python objects to be serialized into a YAML document. The second optional argument is an open file.

如果你需要把几段yaml文档同时写进一个数据流中,请使用yaml.dump_all函数。yaml.dump_all可以接收一个列表或者生成python对象的可序列化生成器(好别扭啊),第二个参数是打开的文件。这完全是对应yaml.load_all的。

yaml.dump supports a number of keyword arguments that specify formatting details for the emitter. For instance, you may set the preferred intendation and width, use the canonical YAML format or force preferred style for scalars and collections.

yaml.dump支持很多种确定格式化发射器的关键字参数(请先无视这句- -#)。比如你可以设置缩进和宽度(指的yaml文档),使用标准yaml格式或者强制优先样式对于标量和收集(请继续无视- -#)。

 dump_all(documents, stream=None, Dumper=<class 'yaml.dumper.Dumper'>, default_style=None, default_flow_style=None, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding='utf-8', explicit_start=None, explicit_end=None, version=None, tags=None)

 #不过对应具体的函数参数可以看出所叙述的几个参数
#cannonical
#indent
#width
#等等

例:

 >>> print yaml.dump(range(50))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
43, 44, 45, 46, 47, 48, 49] >>> print yaml.dump(range(50), width=50, indent=4)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27,
28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47, 48, 49] >>> print yaml.dump(range(5), canonical=True)
---
!!seq [
!!int "",
!!int "",
!!int "",
!!int "",
!!int "",
] >>> print yaml.dump(range(5), default_flow_style=False)
- 0
- 1
- 2
- 3
- 4 >>> print yaml.dump(range(5), default_flow_style=True, default_style='"')
[!!int "", !!int "", !!int "", !!int "", !!int ""]

参数仍需要研究。

#下面没看懂,先记下来,慢慢研究===================================================================

Constructors, representers, resolvers

构造器,描绘器(?),解析器

You may define your own application-specific tags. The easiest way to do it is to define a subclass ofyaml.YAMLObject

你可以自定义一个程序专属标签(tag),定义一个yaml.YAMLObject的子类的最简单方法可以这么干:

 class Monster(yaml.YAMLObject):
yaml_tag = u'!Monster'
def __init__(self, name, hp, ac, attacks):
self.name = name
self.hp = hp
self.ac = ac
self.attacks = attacks
def __repr__(self):
return "%s(name=%r, hp=%r, ac=%r, attacks=%r)" % (
self.__class__.__name__, self.name, self.hp, self.ac,self.attacks)

The above definition is enough to automatically load and dump Monster objects:

上面这个定义的Monster类已经足够用来load和dump了:

 >>> yaml.load("""
... --- !Monster
... name: Cave spider
... hp: [2,6] # 2d6
... ac: 16
... attacks: [BITE, HURT]
... """) Monster(name='Cave spider', hp=[2, 6], ac=16, attacks=['BITE', 'HURT']) >>> print yaml.dump(Monster(
... name='Cave lizard', hp=[3,6], ac=16, attacks=['BITE','HURT'])) !Monster
ac: 16
attacks: [BITE, HURT]
hp: [3, 6]
name: Cave lizard

yaml.YAMLObject uses metaclass magic to register a constructor, which transforms a YAML node to a class instance, and a representer, which serializes a class instance to a YAML node.

yaml.YAMLObject 使用魔法元类注册一个把yaml编码转成类实例的构造器,还有一个把类实例序列化成yaml编码的描述器。

If you don't want to use metaclasses, you may register your constructors and representers using the functionsyaml.add_constructor and yaml.add_representer. For instance, you may want to add a constructor and a representer for the following Dice class:

如果不想使用元类,也可以使用函数yaml.add_constructor和yaml.add_representer来注册构造器和描述器。例如,你可以把一个构造器和描述器加到下面这个Dice类里:

 >>> class Dice(tuple):
... def __new__(cls, a, b):
... return tuple.__new__(cls, [a, b])
... def __repr__(self):
... return "Dice(%s,%s)" % self >>> print Dice(3,6)
Dice(3,6)

The default representation for Dice objects is not nice:

这个Dice对象默认的yaml描述可不怎么好看:

 >>> print yaml.dump(Dice(3,6))

 !!python/object/new:__main__.Dice
- !!python/tuple [3, 6]

Suppose you want a Dice object to represented as AdB in YAML:

好,现在假设你想把Dice对象描述成在yaml里为"AdB"的形式(A,B为变量)。

First we define a representer that convert a dice object to scalar node with the tag !dice and register it.

首先我们定义一个可以把Dice对象转换成带有'!dice'标签节点的描述器,然后注册。

 >>> def dice_representer(dumper, data):
... return dumper.represent_scalar(u'!dice', u'%sd%s' % data) >>> yaml.add_representer(Dice, dice_representer)

Now you may dump an instance of the Dice object:

现在你就可以dump一个Dice实例了:

 >>> print yaml.dump({'gold': Dice(10,6)})
{gold: !dice '10d6'}

Let us add the code to construct a Dice object:

让我们把节点加到Dice对象的构造器中。

 >>> def dice_constructor(loader, node):
... value = loader.construct_scalar(node)
... a, b = map(int, value.split('d'))
... return Dice(a, b) >>> yaml.add_constructor(u'!dice', dice_constructor)

Then you may load a Dice object as well:

然后就可以使用了

 >>> print yaml.load("""
... initial hit points: !dice 8d4
... """) {'initial hit points': Dice(8,4)}

从这里可以看出了,constructor和representer是相对的,一个为load,一个为dump。

博客原文:http://angeloce.iteye.com/blog/385976

yaml在python中的应用简单整理的更多相关文章

  1. YAML 在Python中的配置应用

    环境搭建 YAML语法 语法规则 数据结构 列表数组 原子量 YAML应用 案例 load dump 总结 YAML是一个堪比XML,JSON数据格式的更加方便,简洁的,易于人眼阅读的序列化数据格式. ...

  2. Python中json的简单读写操作

    Python中json的简单读写操作 JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.它基于ECMAScript的一个子集. JSON采用完全独立于语言的 ...

  3. python中argparse模块简单使用

    python中argparse模块简单使用 简介 argparse是python用于解析命令行参数和选项的标准模块.argparse模块的作用是用于解析命令行参数. 使用步骤 1.首先导入该模块 2. ...

  4. python 中面向对象编程简单总结2

    1.python中继承的特点: (1)总是从一个类继承,默认为object类 (2)不要忘记调用super.__init__方法来初始化父类的方法 def __init__(self,args): s ...

  5. YAML 在Python中的应用

    编程免不了要写配置文件,怎么写配置也是一门学问. YAML 是专门用来写配置文件的语言,非常简洁和强大,远比 JSON 格式方便. YAML在python语言中有PyYAML安装包,下载地址:http ...

  6. python中的类简单讲解

    类似其它的语言, Python 中的函数使用小括号( () )调用.函数在调用之前必须先定义.如果函数中没有 return 语句, 就会自动返回 None 对象.      Python 是通过引用调 ...

  7. python 中面向对象编程简单总结3--定制类

    声明:资源来自慕课网python学习课程,以下只是个人学习总结,仅供参考 1.Python类的特殊方法 特征:以  __ 开头并结尾的方法,比如用于print的__str__() , __getatt ...

  8. python中pop(),popitem()的整理

    在python中,列表,字典,有序字典的删除操作有些凌乱,所以决定记录下,以便以后用乱了. 列表: 列表删除有三种方式: l.pop() l.remove() del l[3:8] 已下面的code为 ...

  9. Python中Tk模块简单窗口设计

    Python中Tk和PyQt都可以设计小程序,区别在于:Tk界面美观度相对较差,但由于是Python的内置模块,最终生成的程序大小相比于PyQt较小. import tkinter # 导入TKint ...

随机推荐

  1. JavaScript前端和Java后端的AES加密和解密

    在实际开发项目中,有些数据在前后端的传输过程中需要进行加密,那就需要保证前端和后端的加解密需要统一.这里给大家简单演示AES在JavaScript前端和Java后端是如何实现加密和解密的. 直接上代码 ...

  2. TensorFlow问题:The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.

    1. 问题描述 The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available o ...

  3. VCI_CAN二次开发摘机

    1. 关于CAN滤波的设置的几个参数 PVCI_INIT_CONFIG结构,VCI_InitCAN函数调用时使用 AccCode: 验收码(左对齐) 帧过滤验收码.对经过屏蔽码过滤为"有关位 ...

  4. win10 UWP 应用设置

    win10 UWP 应用设置 简单的把设置需要的,放到微软自带的LocalSettings LocalSettings.Values可以存放几乎所有数据 如果需要存放复合数据,一个设置项是由多个值组成 ...

  5. C# 解析 sln 文件

    我的项目,编码工具 需要检测打开一个工程,获取所有项目. 但是发现原来的方法,如果存在文件夹,把项目放在文件夹中,那么是无法获得项目,于是我就找了一个方法去获得sln文件的所有项目. 原先使用的方法d ...

  6. 利用大白菜制作多系统启动U盘(win+ubuntu+PE+...)

    网上提供的方法很多都过时了,不适用,要不就是讲的不清楚 我结合http://www.xuebuyuan.com/848003.html大神的方案,加以研究,整理出了此篇文章 先看下最终成果: 好了,感 ...

  7. uva1629,Cake Slicing,记忆化搜索

    同上个题一样,代码相似度极高,或者说可以直接用一个模板吧 dp[i,j,p,q]表示一块长为j-i+1,宽为q-p+1,左上角在位置(i,j)上的蛋糕,dp[]表示当前状态下的最优值,然后对该块蛋糕枚 ...

  8. 自学 Python 3 最好的 入门 书籍 推荐(附 免费 在线阅读 下载链接)

    请大家根据自己的实际情况对号入座,挑选适合自己的 Python 入门书籍: 完全没有任何编程基础:01 号书 少量编程基础,不求全,只希望能以最快的速度入门:02 号书 少量编程基础,有一定的英文阅读 ...

  9. How to change your password of your mysql account in WampServer

    #1. use phpmyadmin to login mysql and click the account menu, and then click "Change the passwo ...

  10. bug:翻页

    本章主要分享下,个人测试经历中遇见过的翻页bug 一.列表翻页 1.bug1:去请求翻页page=0,从0页开始算.一般来说page=0 和 page=1的数据是一模一样,所以翻第2页时会发现和第1页 ...