一、YAML语法
YAML是“另一种标记语言”的外语缩写,但为了强调这种语言以数据做为中心,而不是以置标语言为重点,而用返璞词重新命名。它是一种直观的能够被电脑识别的数据序列化格式,是一个可读性高并且容易被人类阅读,容易和脚本语言交互,用来表达资料序列的编程语言。
在Python中使用YAML需要安装PyYAML模块。http://pyyaml.org/wiki/PyYAML
1、块序列描述
块序列就是将描述的元素序列到Python的列表(List)中。
import yaml
obj = yaml.load(
"""
- flash
- alex
- tony
- eric
"""
)
print(obj)
#输出结果:['flash', 'alex', 'tony', 'eric']
obj2 = yaml.load(
"""
-
- flash
- alex
- tony
- eric
-
- china
- USA
- Japan
"""
)
#输出结果:[['flash', 'alex', 'tony', 'eric'], ['china', 'USA', 'Japan']]
2、块映射描述
块映射就是将描述的元素序列到Python的字典(dict)中,格式为“key:value”。
import yaml
print(yaml.load("""
name: Vorlin Laruknuzum
sex: Male
class: Priest
title: Acolyte
hp: [32, 71]
sp: [1, 13]
gold: 423
inventory:
- a Holy Book of Prayers (Words of Wisdom)
- an Azure Potion of Cure Light Wounds
- a Silver Wand of Wonder
""")
)
# 输出结果:{'name': 'Vorlin Laruknuzum', 'hp': [32, 71], 'class': 'Priest', 'sp': [1, 13], 'sex': 'Male', 'inventory': ['a Holy Book of Prayers (Words of Wisdom)', 'an Azure Potion of Cure Light Wounds', 'a Silver Wand of Wonder'], 'gold': 423, 'title': 'Acolyte'}