我有一个word文件,里面有表格。目标是扫描XML(使用lxml
)并生成{formTag:formValue}
字典。它变得更复杂一些,因为表单可以嵌套在最初生成的其他重复表单中
{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)
如何确定放置字段的最底层,以便字典正确嵌套?
要在任何字典中查找最后一个嵌套,必须使用递归关系:
因此,您需要考虑的主要问题是如何终止递归关系,以便最终得到所需的dict
相关问题 更多 >
编程相关推荐