鍍金池/ 問答/Python  Linux  網(wǎng)絡(luò)安全/ python怎么解析yaml文件?

python怎么解析yaml文件?

用python解析一個yaml文件。

name: "MyName !!"
name2 : !haha
  note : "name2"
massage: !description
  age : 18
  home:
    - SH
    - BJ
    - GZ

比如我現(xiàn)在需要拿到home的內(nèi)容,需要怎么寫腳本呢?
之前寫過,都卡在“!description”上面,Exception說不能解決這個自定義類型tag。
我之前的解析代碼:

import yaml

with open("./a.yml") as f:
    x = yaml.load(f)

print(x)

求助大神解決辦法。

回答
編輯回答
編輯回答
做不到

首先安裝PyYAML

pip install PyYAML

然后你需要自定義tag,代碼如下

import yaml


class HaHa(yaml.YAMLObject):
    yaml_tag = '!haha'

    def __init__(self, note):
        self.note = note

    def __repr__(self):
        return "%s(note=%r)" % (self.__class__.__name__, self.note)


class Description(yaml.YAMLObject):
    yaml_tag = '!description'
    def __init__(self, age, home):
        self.age = age
        self.home = home
    def __repr__(self):
        return "%s(age=%r, home=%r)" % (
                self.__class__.__name__, self.age, self.home)

獲取home的值:

if __name__ == '__main__':
    with open('test.yaml', 'r') as f:
        yaml_data = yaml.load(f)
    print(yaml_data)
    print(yaml_data.get('massage').home)

輸出:

{'name': 'MyName !!', 'name2': HaHa(note='name2'), 'massage': Description(age=18, home=['SH', 'BJ', 'GZ'])}

['SH', 'BJ', 'GZ']

test.yaml是你上面貼出來的數(shù)據(jù)

PyYAML的文檔:http://pyyaml.org/wiki/PyYAML...

2018年8月13日 20:08
編輯回答
帥到炸
import yaml
with open('exmaple.yaml', 'r') as f:
    exmaple = yaml.load(f)
home = exmaple["home"]
    print home 
    
 這樣試一下
2018年2月1日 07:04