【问题标题】:Parse text (or ASCII) directory tree to Python object将文本(或 ASCII)目录树解析为 Python 对象
【发布时间】:2019-02-23 03:01:20
【问题描述】:

这或多或少是与List directory tree structure in python? 和这个答案https://stackoverflow.com/a/51991554/7422721 的反向问题

鉴于我们有文本艺术风格的目录树(ASCII,但不限于),作为tree 程序或等效 Python 脚本的输出生成:

a/
├── b/
│   └── c/
│       ├── file_1
│       └── file_2
└── d/

每个文件名都以'/', '=', '*', '@', '|' or '>' 之一结束,指示文件类型,与ls -Ftree -F 约定一样。所以以/结尾的文件名是目录,=是socket等。如果没有结尾,我们假设它是普通文件。

如何将其读回本机数据结构,例如:

[
  "a": [
    "b": [
      "c": [
        "file_1", "file_2"
      ]
    ],
    "d": []
  ]
]  

或者其他可以在内存文件系统中表示的对象?

这里的目标是为操作磁盘上文件的脚本创建可读的单元测试。

【问题讨论】:

  • 所以你想把 ASCII 树转换成字典?
  • @Alderven 这有点具体 - 我想将文本树转换为 Python 对象。它不一定必须是嵌套列表/字典,但我认为它会是最简单的实现。

标签: python tree filesystems


【解决方案1】:

我能够将示例树从您的问题转换为 dict 格式:

{'a': {'b': {'c': {'file_1': {}, 'file_2': {}}}, 'd': {}}}

脚本:

import re

def find_children(tree):
    result = {}
    for i, line in enumerate(tree.split('\n')):
        child = re.findall('^\w+', line)
        if child:
            parent = child[0]
            child_tree = '\n'.join([x[len(parent)+3:] for x in tree.split('\n')[i+1:]])
            result[parent] = find_children(child_tree)
    return result

with open('tree.txt', 'r', encoding='utf-8') as f:
    tree_dict = find_children(f.read())

【讨论】:

  • 我喜欢忽略像├ └ │ ─ 这样的特殊字符的想法。但它会在比提供的带有 a、b、c 的示例更复杂的情况下失败。例如,尝试在 tree /etc 的输出上使用它:)
猜你喜欢
  • 1970-01-01
  • 2016-09-20
  • 2013-03-17
  • 2011-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多