将字典展平为格式化字符串
flatten dictionary to formatted string
这个问题我卡了很久
假设我们有一个 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))))))
这个问题我卡了很久
假设我们有一个 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))))))