【问题标题】:How to convert text to "nested" dictionary?如何将文本转换为“嵌套”字典?
【发布时间】:2021-05-18 14:57:36
【问题描述】:

我正在尝试将缩进文本转换为 python 中的嵌套字典列表 受此线程的启发 Creating a tree/deeply nested dict from an indented text file in python 它帮助我开始,但我仍然未能达到预期的结果

indented_text = """
# Level 1
## Level 2
### Level 3
#### Level 4
##### Level 5
###### Level 6
##### Level 5
#### Level 4
##### Level 5
###### Level 6
### Level 3
#### Level 4
## Level 2
### Level 3
#### Level 4
#### Level 4
### Level 3
"""
class Node:
    def __init__(self, indented_line):
        # self.t = t
        # self.d = d
        # self.p = {}
        # self.v = v ---------
        # self.c = [] ------
        self.t = 'list_item'
        self.d = indented_line.index('# ') # len(indented_line) - len(indented_line.lstrip())
        self.p = {}
        self.v = indented_line[self.d + 1:].strip()
        self.c = []

    def add_children(self, nodes):
        childlevel = nodes[0].d
        while nodes:
            node = nodes.pop(0)
            if node.d == childlevel: # add node as a child
                self.c.append(node)
            elif node.d > childlevel: # add nodes as grandchildren of the last child
                nodes.insert(0,node)
                self.c[-1].add_children(nodes)
            elif node.d <= self.d: # this node is a sibling, no more children
                nodes.insert(0,node)
                return

root = Node('# root')
root.add_children([Node(line) for line in indented_text.splitlines() if line.strip()])

现在我需要输出

{
    "t": "heading",
    "d": 1,
    "p": {},
    "v": "Level 1",
    "c": [
        {
            "t": "heading",
            "d": 2,
            "p": {},
            "v": "Level 2",
            "c": [
                {
                    "t": "heading",
                    "d": 3,
                    "p": {},
                    "v": "Level 3",
                    "c": [
                        {
                            "t": "heading",
                            "d": 4,
                            "p": {},
                            "v": "Level 4",
                            "c": [
                                {
                                    "t": "heading",
                                    "d": 5,
                                    "p": {},
                                    "v": "Level 5",
                                    "c": [
                                        {
                                            "t": "heading",
                                            "d": 6,
                                            "p": {},
                                            "v": "Level 6"
                                        }
                                    ]
                                },
                                {
                                    "t": "heading",
                                    "d": 5,
                                    "p": {},
                                    "v": "Level 5"
                                }
                            ]
                        },
                        {
                            "t": "heading",
                            "d": 4,
                            "p": {},
                            "v": "Level 4",
                            "c": [
                                {
                                    "t": "heading",
                                    "d": 5,
                                    "p": {},
                                    "v": "Level 5",
                                    "c": [
                                        {
                                            "t": "heading",
                                            "d": 6,
                                            "p": {},
                                            "v": "Level 6"
                                        }
                                    ]
                                }
                            ]
                        }
                    ]
                },
                {
                    "t": "heading",
                    "d": 3,
                    "p": {},
                    "v": "Level 3",
                    "c": [
                        {
                            "t": "heading",
                            "d": 4,
                            "p": {},
                            "v": "Level 4"
                        }
                    ]
                }
            ]
        },
        {
            "t": "heading",
            "d": 2,
            "p": {},
            "v": "Level 2",
            "c": [
                {
                    "t": "heading",
                    "d": 3,
                    "p": {},
                    "v": "Level 3",
                    "c": [
                        {
                            "t": "heading",
                            "d": 4,
                            "p": {},
                            "v": "Level 4"
                        },
                        {
                            "t": "heading",
                            "d": 4,
                            "p": {},
                            "v": "Level 4"
                        }
                    ]
                },
                {
                    "t": "heading",
                    "d": 3,
                    "p": {},
                    "v": "Level 3"
                }
            ]
        }
    ]
}

我无法完成并获得所需的输出...

【问题讨论】:

  • 你得到什么输出?它与您的预期有何不同?您尝试过什么调试来解决问题?你能把你的代码压缩成一个minimal reproducible example 并格式化你的预期输出以便它可读吗?
  • 为什么/你添加的那些手册 c、v、t、d、p 是什么?
  • @PranavHosangadi 输出是我的问题我不知道如何将其转换为可打印的 dict / json 字符串
  • @TenaciousB 我不确定你的意思,这是我需要输出的格式
  • 你的意思是问how to serialize a class to JSON

标签: python json dictionary parsing


【解决方案1】:

我能够通过使用解决我的问题

json.dumps(root, default=lambda v: v.__dict__)

感谢大家的参与和https://stackoverflow.com/users/843953/pranav-hosangadi 为我指明正确的方向

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2020-09-03
    • 2013-12-07
    • 2019-12-09
    相关资源
    最近更新 更多