Python 删除路径的一部分

Python 删除路径的一部分,python,regex,Python,Regex,我有以下数据: /​share/​Downloads/​Videos/​Movies/​Big.Buck.Bunny.​720p.​Bluray.​x264-BLA.​torrent/Big.Buck.Bunny.​720p.​Bluray.​x264-BLA 然而,我不想要“大兔子”。​720便士。​布鲁雷。​x264 BLA.torrent/“在其中,我希望路径如下所示: /​share/​Downloads/​Videos/​Movies/Big.Buck.Bunny.​720p.​Bl

我有以下数据:

/​share/​Downloads/​Videos/​Movies/​Big.Buck.Bunny.​720p.​Bluray.​x264-BLA.​torrent/Big.Buck.Bunny.​720p.​Bluray.​x264-BLA
然而,我不想要“大兔子”。​720便士。​布鲁雷。​x264 BLA.torrent/“在其中,我希望路径如下所示:

/​share/​Downloads/​Videos/​Movies/Big.Buck.Bunny.​720p.​Bluray.​x264-BLA
对于正则表达式,我基本上想对包含*.torrent./的任何内容进行数学运算,如何在regexp中实现这一点

谢谢

我基本上想计算任何包含*.torrent./的内容,如何在regexp中实现这一点

您可以使用:

[^/]*\.torrent/

假设最后一个
是一个输入错误。

您可以不使用regexp执行此操作:

>>> x = unicode('/share/Downloads/Videos/Movies/Big.Buck.Bunny.720p.Bluray.x264-BLA.torrent/Big.Buck.Bunny.720p.Bluray.x264-BLA')
>>> x.rfind('.torrent')
66
>>> x[:x.rfind('.torrent')]
u'/share/Downloads/Videos/Movies/Big.Buck.Bunny.720p.Bluray.x264-BLA'

你甚至不需要正则表达式。您可以使用和:

其中
path
是文件的原始路径

或者,您也可以按如下方式使用:

dirname, filename = os.path.split(path)
os.path.join(os.path.dirname(dirname), filename)

注意,假设您要删除的是包含问题示例中路径中的文件的目录名,则此操作有效。

给定
path='/share/Downloads/Videos/Movies/Big.Buck.Bunny.720p.Bluray.x264 BLA.torrent/Big.Buck.Bunny.720p.Bluray.x264 BLA'

您可以使用正则表达式来完成它,如下所示

re.sub("/[^/]*\.torrent/","",path)
您也可以不使用regex作为

'/'.join(x for x in path.split("/") if x.find("torrent") == -1)

你的问题有点模糊和不清楚,但这里有一种方法可以去除你想要的东西:

import re
s = "/share/Downloads/Videos/Movies/Big.Buck.Bunny.720p.Bluray.x264-BLA.torrent/Big.Buck.Bunny.720p.Bluray.x264-BLA"

c = re.compile("(/.*/).*?torrent/(.*)")
m = re.match(c, s)
path = m.group(1)
file = m.group(2)
print path + file

>>> ## working on region in file /usr/tmp/python-215357Ay...
/share/Downloads/Videos/Movies/Big.Buck.Bunny.720p.Bluray.x264-BLA

您可以在文件结构中移动它,或者重命名父文件夹。这总是比较容易的。我们不是在谈论对文件系统进行更改,这是为了不同的目的。不是真的,我的工作要求我处理法律洪流,比如这部免费电影。谢谢!我刚刚在中尝试了这个,但不幸的是它没有起作用:(@FLX,它工作得很好:用空字符串替换匹配项以获得您要查找的结果。(请注意,您粘贴的路径中有一些“隐藏”字符,至少对我来说会把事情搞砸。)谢谢,但我正在寻找一个正则表达式:)+1以提供最好的(最健壮的)解决眼前问题的方法。
import re
s = "/share/Downloads/Videos/Movies/Big.Buck.Bunny.720p.Bluray.x264-BLA.torrent/Big.Buck.Bunny.720p.Bluray.x264-BLA"

c = re.compile("(/.*/).*?torrent/(.*)")
m = re.match(c, s)
path = m.group(1)
file = m.group(2)
print path + file

>>> ## working on region in file /usr/tmp/python-215357Ay...
/share/Downloads/Videos/Movies/Big.Buck.Bunny.720p.Bluray.x264-BLA