#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
>>>
```