2009-07-14 62 views
1

路径比方说,我有看起来像这样的目录路径:关于产品在Python

this/is/the/basedir/path/a/include 
this/is/the/basedir/path/b/include 
this/is/the/basedir/path/a 
this/is/the/basedir/path/b 

在Python,我怎么能起来拆分这些路径,使他们看起来是这样,而不是:

a/include 
b/include 
a 
b 

如果我运行os.path.split这样的(路径)[1]它会显示:

include 
include 
a 
b 

我应该怎么在这里尝试了,我应该寻找在索姆e正则表达式命令还是可以在没有它的情况下完成?提前致谢。

编辑所有:我解决它使用正则表达式,真他妈方便的工具:)

+0

目前还不清楚你如何确定在哪里拆分路径。例如,你想用一些/ other/basedir /和/ stuff/that/I/include来做什么? – 2009-07-14 13:34:18

回答

3

也许这样的事情,取决于如何硬编码的前缀是:

def removePrefix(path, prefix): 
    plist = path.split(os.sep) 
    pflist = prefix.split(os.sep) 
    rest = plist[len(pflist):] 
    return os.path.join(*rest) 

用法:

print removePrefix("this/is/the/basedir/path/b/include", "this/is/the/basedir/path") 
b/include 

假设您位于目录分隔符(os.sep)确实是正斜杠的平台上)。

此代码尝试将路径处理为比单纯字符串更高级别的事情。尽管这不是最理想的,但你可以(或应该)做更多的清洁和标准化以保证更安全。

1

什么partition
它在sep第一次出现时分割字符串,并返回包含分隔符之前的部分,分隔符本身和分隔符之后的部分的3元组。如果未找到分隔符,则返回包含该字符串本身的三元组,然后返回两个空字符串。

data = """this/is/the/basedir/path/a/include 
this/is/the/basedir/path/b/include 
this/is/the/basedir/path/a 
this/is/the/basedir/path/b""" 
for line in data.splitlines(): 
    print line.partition("this/is/the/basedir/path/")[2] 

#output 
a/include 
b/include 
a 
b 

更新了由作者的新评论:
它看起来像你需要通过rsplit为不同的目录目录的endsWith是否“包括”不:

import os.path 
data = """this/is/the/basedir/path/a/include 
this/is/the/basedir/path/b/include 
this/is/the/basedir/path/a 
this/is/the/basedir/path/b""" 
for line in data.splitlines(): 
    if line.endswith('include'): 
     print '/'.join(line.rsplit("/",2)[-2:]) 
    else: 
     print os.path.split(line)[1] 
     #or just 
     # print line.rsplit("/",1)[-1] 
#output 
a/include 
b/include 
a 
b 
1

也许是这样的:

result = [] 

prefix = os.path.commonprefix(list_of_paths) 
for path in list_of_paths: 
    result.append(os.path.relpath(path, prefix)) 

这只在2.6。 2.5和之前的relapath只在路径是当前工作目录的情况下才工作。

0

尽管标准并非100%清晰,但从OP的评论看来,关键问题在于路径的最后一个组件是否以“include”结尾。如果是这种情况,并且在最后一个组件是例如“dontinclude”(作为另一个通过尝试字符串匹配而不是路径匹配的答案),我建议:

def lastpart(apath): 
    pieces = os.path.split(apath) 
    final = -1 
    if pieces[-1] == 'include': 
     final = -2 
    return '/'.join(pieces[final:])