问题描述
我在这个问题上坚持了很长时间。
假设我们有一个python字典,如下所示:
d = {'TOP': [{'S': [{'NP-TMP': [{'NP': [{'DT': ['This']},{'NN': ['time']}]},{'ADVP': [{'RP': ['around']}]}]},{'NP-SBJ': [{'PRP': ['they']}]},{'VP': [{'VBP': ["'re"]},{'VP': [{'VBG': ['moving']},{'ADVP': [{'RB': ['even']},{'RBR': ['faster']}]}]}]}]}]}
我想将其转换为以下格式:
(((((This)(time))((around)))((they))(('re)((moving)((even)(faster))))))
我尝试了以下代码,但无法继续进行操作。
for tree in d.values():
for i,j in tree[0].items():
for n in j:
for p in n.items():
print(p)
解决方法
递归生成器可以工作(虽然不是很好,但是...)
def sub(dct):
for lst in dct.values():
for item in lst:
if isinstance(item,str):
yield f"{item}"
elif isinstance(item,dict):
yield "("
yield from sub(item)
yield ")"
elif isinstance(item,list):
assert len(item) == 1
yield f"{item[0]}"
else:
pass
结果是:
r = f"({''.join(sub(d))})"
print(r)
# (((((This)(time))((around)))((they))(('re)((moving)((even)(faster))))))