【问题标题】:Python regex print list of directoryPython regex 打印目录列表
【发布时间】:2021-01-04 13:03:15
【问题描述】:

我有一个目录列表作为 python 中的列表,其中包含以下数据:

/a
/a/b
/a/b/1
/a/b/2
/a/b/3
/a/c
/a/c/1
/a/c/2
/a/c/3
/a/d
/a/d/1
/a/d/2
/f
/f/g
/f/g/h
/f/g/i
/f/g/j

我想以以下格式显示输出:

/a
    /b
        /1
        /2
        /3
    /c
        /1
        /2
        /3
    /d
        /1
        /2
/f
    /g
        /h
        /i
        /j

我正在使用以下 python 函数,但它打印的输出不一致:

def formatVFS(lst):
    for line in lst:
        l1 = list(lst)
        l2 = []
        if re.search(r'^/\w+', line) != None:
            temp = re.search(r'^/\w+', line).group()
            print '\t\t', temp
            for line2 in l1:
                if line2.startswith(temp):
                    lst.remove(line2)
                    line2 = line2.replace(temp, '')
                    if line2!= '':
                        l2.append(line2)
                        print '\t\t\t',line2
            formatVFS(l2)

有什么建议吗?

【问题讨论】:

  • “它正在打印不一致的输出”请在您的问题中包含它
  • 另附注:print '\t... 是 python2 语法。 Python 2 reached EOL earlier this year. 除非你有充分的理由使用 Python 2,否则你应该使用 Python 3。
  • 我必须在遗留系统中使用这个程序。所以不能改变Python的版本。安装的python版本是2.7.5
  • 这是使用 Python 2 的好理由 :)

标签: python regex for-loop directory


【解决方案1】:

请尝试下面的程序,这会搜索并用制表符替换不在行尾的\/\w+。假设文件夹按预期顺序排列。如果不是,您可以在显示之前对其进行排序。

import re
l=["/a","/a/b","/a/b/1","/a/b/2","/a/b/3","/a/c","/a/c/1","/a/c/2","/a/c/3","/a/d","/a/d/1","/a/d/2","/f","/f/g","/f/g/h","/f/g/i","/f/g/j"]
for i in l:
    print(re.sub(r"\/\w+(?=\/(?!$))","\t",i))

输出

/a
        /b
                /1
                /2
                /3
        /c
                /1
                /2
                /3
        /d
                /1
                /2
/f
        /g
                /h
                /i
                /j

【讨论】:

  • 感谢@Liju 的回答。该程序在给定的输入下运行良好,但这种类型的数据会出错 / /work /work/archive /work/pull /work/push /work/autowork /work/autodone /work/distribution /work/distribution/ 1 /work/distribution/2 /work/distribution/3 /work/distribution/4 /work/distribution/5 /work/distribution/6 /work/distribution/7 /work/distribution/8 /work/distribution/9 /工作/分发/10 /工作/触发器
  • @FarmanAhmed 在您寻求帮助时,总是最好提供尽可能多的相关细节“它在第 x 行给出这样那样的错误”“它打印 abc 而不是 xyz” 比说“好多了它不起作用”。
  • @FarmanAhmed,我已经更新了上面的程序。请检查。
  • @Liju 这种类型的数据仍然会出错 /zzzAdmin /zzzAdmin/zzzAdmin_MFT1.0-vfs /zzzAdmin/zzzAdmin_MFT1.0-vfs/adhoc1113 /zzzAdmin/zzzAdmin_MFT1 .0-vfs/adhoc/fromSSC1114 /zzzAdmin/zzzAdmin_MFT1.0-vfs/adhoc/toSSC1115 /zzzAdmin/zzzAdmin_MFT1.0-vfs/fromSSC 1111 /zzzAdmin/zzzAdmin_MFT1.0-vfs/fromSSC/archive1112 /zzzAdmin/zzzAdmin_MFT1.0-vfs/toSSC1109
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-18
  • 1970-01-01
  • 2016-03-31
  • 1970-01-01
相关资源
最近更新 更多