def lookup(d, key):
found = False
for child in d:
if found : return child.text
if child.tag == 'key' and child.text == key :
found = True
return None
stuff = ET.parse(fname)
all = stuff.findall('dict/dict/dict')
print('Dict count:', len(all))
for entry in all:
if ( lookup(entry, 'Track ID') is None ) : continue
name = lookup(entry, 'Name')
artist = lookup(entry, 'Artist')
album = lookup(entry, 'Album')
count = lookup(entry, 'Play Count')
rating = lookup(entry, 'Rating')
length = lookup(entry, 'Total Time')
if name is None or artist is None or album is None :
continue
def lookup(d, key):
found = False
for child in d:
if found : return child.text
if child.tag == 'key' and child.text == key :
found = True
return None
这一段看不明白,请教大神。
方法有两个形参,一个是d(一个list),一个是key(string 或者 int 或者其它类型)。进入循环前先把found的值改为false,然后开始遍历d内的成员。如果d的某一个成员的tag属性值为“key”(字符串),并且它的text属性值等于形参key。那么就会使found置为true,在下个循环开始的时候会将下一个d成员的text属性的值作为返回值。如果一直不存在匹配,则遍历完d的所有成员后返回None。
如果d的某一个成员的tag属性值为“key”(字符串),并且它的text属性值等于形参key。那么就会使found置为true,在下个循环开始的时候会将下一个d成员的text属性的值作为返回值。