Разобрать строку путей в JSON объект - PullRequest
0 голосов
/ 03 февраля 2020

У меня есть набор строк (1), которые представляют граф / дерево решений (2). Каждый символ представляет путь вдоль графика.

###1###
'0A1B'
'0A1A'
'0A0A'
'0A0A'
'0B10'
'0B11'

enter image description here

Я хочу обработать этот список строк в Python, чтобы создать JSON переменная со следующей структурой (3):

###3###
{
"name": "0",
"count": 6,
"children": [
    {
    "name": "A",
    "count": 4,
    "children": [
        {"name": "0",
        "count": 2,
        "children": [
            {"name": "A", "count": 2}
        ]
        },
        {"name": "1",
        "count": 2,
        "children": [
            {"name": "A", "count": 1},
            {"name": "B", "count": 1}
        ]
        }
    ]
    },
    {
    "name": "B",
    "count": 2,
    "children": [
        {"name": "1",
        "count": 2,
        "children": [
            {"name": "0", "count": 1},
            {"name": "1", "count": 1}
        ]
        }
    ]
    }
]
}

Есть ли библиотека, которая может сделать это проще? Я могу использовать библиотеку json для создания json объектов, но не знаю, как разобрать строку. Вроде рекурсивная функция нужна?

1 Ответ

1 голос
/ 03 февраля 2020

Не думаю, что вам нужны какие-либо специфические c библиотеки, кроме встроенных json:

import json


def dict_tree(ss):
    # there has to be at least one string and it has to have at least 1 character
    assert ss and ss[0]
    result = {'name': ss[0][0], 'count': 0}
    for s in ss:
        # all strings should start with the same character 
        # (the suggested data structure does not support more than one name at the root level)
        assert s and s[0] == result['name']
        p = result
        p['count'] += 1
        for ch in s[1:]:
            if 'children' not in p:
                p['children'] = []
            for child in p['children']:
                if child['name'] == ch:
                    p = child
                    break
            else:
                p['children'].append({'name': ch, 'count': 0})
                p = p['children'][-1]
            p['count'] += 1
    return result


def main():
    strings = [
        '0A1B',
        '0A1A',
        '0A0A',
        '0A0A',
        '0B10',
        '0B11'
    ]
    print(json.dumps(dict_tree(strings), indent=4))


main()
...