python处理合并的yaml文件, 递归读取字典获取指定字段,用re包清除字段

#1 使用python递归读数据和字典,主要用于处理yaml文件

如下代码,递归读取字典,当其中的值为list的时候,接着递归:

```

import yaml

import os

import re

#the requirement to find image:

#when the value is a list or dic, you need to drive into it, and to see if images in it

def travelDict(dict_a):

if isinstance(dict_a,dict) : #使用isinstance检测数据类型

for x in range(len(dict_a)):

temp_key = dict_a.keys()[x]

temp_value = dict_a[temp_key]

if(temp_key == "image"):

print"%s : %s" %(temp_key,temp_value)

#judge the value's format of the key

if isinstance(temp_value, list):

for dic in temp_value:

travelDict(dic)

travelDict(temp_value)

def getImages(fd):

strCont = fd.read()

#convert to dict:

dicCont = yaml.load_all(strCont)

for dic in dicCont:

print(dic)

print("\n\n")

travelDict(dic)

print("\n\n")

if __name__ == "__main__":

#open the target yaml file:

#getImages(open("./deamonsetSample.yaml", "r"))

getImages(open("./test.yaml", "r"))

```

注意,使用load_all就是为了一次读取多个合并的yaml文件;

# 2 使用python的re包来清除字符

```

Python 2.7.15+ (default, Nov 27 2018, 23:36:35)

[GCC 7.3.0] on linux2

Type "help", "copyright", "credits" or "license" for more information.

>>> import re

>>> print re.sub('[\r\t\n\'\" ]', "", "hello \n \thello kiss")

hellohellokiss

>>>

```

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值