YAML+PyYAML笔记 3 | YAML集合、结构、标量、标记使用
  NHjqxS4aAIAZ 2023年11月02日 26 0

(3 | YAML集合、结构、标量、标记使用)

1 集合

YAML 支持三种集合类型:列表,映射和集。

1.1 列表

  • 列表是一种序列结构,它使用连字符“-”表示;
  • 如下三个元素的列表,元素之间用“-”
fruit:
 - apple
 - rubber
 - pear
  • 使用Pyyaml解析:
# 解析
with open("config_jihe.yaml") as f:
    yaml_data2 = yaml.load(f, Loader=yaml.FullLoader)
print(yaml_data2)

# 输出
{'fruit': ['apple', 'rubber', 'pear']}

1.2 映射

  • 即一种键值对结构,它使用冒号“:”表示;
  • 如下:
fruit:
  - apple
  - rubber
  - pear

vegetable:
  green: cucumber
  red: tomato
  yellow: corn
  • 使用Pyyaml解析:
{'fruit': ['apple', 'rubber', 'pear'], 'vegetable': {'green': 'cucumber', 'red': 'tomato', 'yellow': 'corn'}}

1.3 集

  • 无序不重复的数据类型;
  • 用大括号“{}”表示;
tree: {poplar, willow, pine}
{'tree': {'poplar': None, 'willow': None, 'pine': None}}

2 结构

  • 可用于任何数据类型的复杂性结构;
  • 包括集合和其他数据类型。

2.1 多行结构

  • 表示复杂数据类型的方式;
  • 如下:
vegetable:
  green: cucumber
  red: tomato
  yellow: corn

tree:
  one: poplar
  two: willow
  three: pine
{'vegetable': {'green': 'cucumber', 'red': 'tomato', 'yellow': 'corn'}, 'tree': {'one': 'poplar', 'two': 'willow', 'three': 'pine'}}

2.2 单行结构

  • 在一行上表示复杂的结构:
  • 如下:
data: {vegetable: {green: cucumber, red: tomato, yellow: corn}, tree: {one: poplar, two: willow, three: pine}}
{'data': {'vegetable': {'green': 'cucumber', 'red': 'tomato', 'yellow': 'corn'}, 'tree': {'one': 'poplar', 'two': 'willow', 'three': 'pine'}}}

3 字面量

  • 字面量可以表示字符串、数字、布尔值、null 值等;
# 字符串:在双引号中使用转义符号来表示特殊字符
str: "Hello,\\nWorld!"

# 数字:可以表示整数和浮点数
int: 88888
float: 3.141592653

# 布尔值:可以使用true和false表示
boolean: true

# null 值:使用 null 来表示空值
empty: null
  • 使用Pyyaml解析:
{'str': 'Hello,\\nWorld!', 'int': 88888, 'float': 3.141592653, 'boolean': True, 'empty': None}

4 标量

  • 分为单引号、双引号和无引号;
# 单引号:表示精确字符串,不会进行转义
single: 'Hello,\nworld!'

# 双引号:表示标准字符串,可以进行转义
double: "Hello,\\nworld!"

# 无引号:可以识别特殊字符,但空格会自动被转义成字符串
none: hello world
{'single': 'Hello,\\nworld!', 'double': 'Hello,\\nworld!', 'none': 'hello world'}

5 标记

# !!str:表示字符串类型。如:
key: !!str string

# !!int:表示整数类型。如:
key: !!int 123

# !!float:表示浮点数类型。如:
key: !!float 3.14

# !!bool:表示布尔类型。如:
key: !!bool true

# &name:为数据定义一个锚点,可以在后面使用锚点引用。如:
person: &p
name: xiaozhang
age: 88

student:
<<: *p
grade: 100

6 指示符

  • 指示符包括用于描述YAML文档内容的特殊语义:
编号 字符 功能
1 _ 表示块序列条目
2 ? 表示映射键
3 : 表示映射值
4 , 表示流集合条目
5 [ 开始流序列
6 ] 结束流序列
7 { 启动流映射
8 } 结束流映射
9 # 表示注释
10 & 表示节点的锚属性
11 * 表示别名节点
12 ! 表示节点的标签
13 Ι 表示一个字面块标量
14 > 表示折叠块标量
15 ' 单引号围绕引用的流标量
16 " 双引号包围双引号流标量
17 % 表示使用的指令
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
NHjqxS4aAIAZ
最新推荐 更多