2
我有一个带有窗体的字文件。目标是扫描XML(使用lxml
)并生成{formTag:formValue}
字典。它得到稍微更加复杂,因为形式可以嵌套在其它重复形式,其initally产生从Word XML嵌套字典
{topLevelFormTag:formTag1+formValue1+formTag2+formValue2, formTag1:formValue1, formTag2:formValue2}
然而,我们的目标是最终与
{topLevelFormTag:{formTag1:formValue1, formTag2:formValue2}}
正如我通过文件搜索(for field in xmlroot.iter(TAG_FIELD):
)我填写了两本字典; parents
和descendants
与parents[field] = field.getparents(
)和descendants[field] = list(field.iterdescendants())
。以下是我将所有字段的字典合并到嵌套字典中的方法。如果只有一层嵌套,它可以很好地工作,但是,它会失败并带有更多的层次。它失败了,因为嵌套表单在的所有的后代中,因此它可以作为任何上层的子级放置。
for ptag in parents:
for dtag in descendants:
if parents[ptag] in descendants[dtag]:
print "{} is a descendant of {}".format(ptag, dtag)
try:
fields[dtag][ptag] = fields[ptag]
del fields[ptag]
except TypeError:
fields[dtag] = {ptag: fields[ptag]}
del fields[ptag]
except KeyError:
print "!!!{}:{}!!!".format(ptag, dtag)
如何确定最下方水平放置在这样一个领域,我的字典里是正确的嵌套?