文件名之间的通用路径(如在git中)

时间:2015-04-04 06:20:43

标签: python path

我注意到git commit有一种以类似regex的方式显示源/目标路径的奇特方式,例如:

wallpapers/{8.jpg => 1.jpg}

是否有任何Python模块可以产生这种"缩短"?例如,我希望有类似的东西:

/home/user/doc.pdf => /home/user/Desktop/doc.pdf

变成了

/home/user/{doc.pdf => Desktop/doc.pdf}

或者甚至

/home/user/{ => Desktop}/doc.pdf

来自git的另一个例子

{deprecated => deprecated code}/Binary.cs 

1 个答案:

答案 0 :(得分:1)

我可以修改How to circumvent the fallacy of Python's os.path.commonprefix?的答案以产生此结果:

def commonprefix(l):
    # this unlike the os.path.commonprefix version
    # always returns path prefixes as it compares
    # path component wise
    cp = []
    ls = [p.split('/') for p in l]
    ml = min( len(p) for p in ls )

    for i in range(ml):

        s = set( p[i] for p in ls )         
        if len(s) != 1:
            break

        cp.append(s.pop())

    return '/'.join(cp+['{'+' => '.join('/'.join(p[i:]) for p in ls)+'}'])

print commonprefix(['wallpapers/8.jpg','wallpapers/1.jpg'])
print commonprefix(['/home/user/doc.pdf', '/home/user/Desktop/doc.pdf'])

打印:

wallpapers/{8.jpg => 1.jpg}
/home/user/{doc.pdf => Desktop/doc.pdf}