【问题标题】:flatten dictionary to formatted string将字典展平为格式化字符串
【发布时间】:2020-11-05 09:00:27
【问题描述】:

我被这个问题困扰了很长时间。

假设我们有一个如下的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)

【问题讨论】:

    标签: python dictionary nlp parse-tree


    【解决方案1】:

    递归生成器可以工作(虽然不是很好......)

    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))))))
    

    【讨论】:

      猜你喜欢
      • 2019-01-08
      • 1970-01-01
      • 1970-01-01
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      • 2021-06-17
      • 1970-01-01
      • 2010-10-16
      相关资源
      最近更新 更多