一、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'}
