gpt4 book ai didi

Python 在整个列表中查找字符串的公共(public)部分并将其从每个项目中删除

转载 作者:行者123 更新时间:2023-12-05 03:08:04 25 4
gpt4 key购买 nike

我有一个类似于下面的文件目录列表:

path/new/stuff/files/morefiles/A/file2.txt
path/new/stuff/files/morefiles/B/file7.txt
path/new/stuff/files/morefiles/A/file1.txt
path/new/stuff/files/morefiles/C/file5.txt

我正在尝试从每个列表中删除相同 路径的开头,然后从每个文件中删除它。

列表可以是任意长度,在示例中我将尝试将列表更改为:

A/file2.txt
B/file7.txt
A/file1.txt
C/file5.txt

re.sub(r'.*I', 'I', filepath)filepath.split('_', 1)[-1] 这样的方法 可用于替换,但我不确定如何在文件路径列表中找到公共(public)部分

注意:

我正在使用 Windows 和 python 3

最佳答案

答案的第一部分在这里:Python: Determine prefix from a set of (similar) strings

使用 os.path.commonprefix() 查找字符串的最长公共(public)(第一部分)

选择与该答案相同的列表部分的代码是:

# Return the longest prefix of all list elements.
def commonprefix(m):
"Given a list of pathnames, returns the longest common leading component"
if not m: return ''
s1 = min(m)
s2 = max(m)
for i, c in enumerate(s1):
if c != s2[i]:
return s1[:i]
return s1

现在您所要做的就是使用切片从列表中的每个项目中删除结果字符串

这导致:

# Return the longest prefix of all list elements.
def commonprefix(m):
"Given a list of pathnames, returns the longest common leading component"
if not m: return ''
s1 = min(m)
s2 = max(m)
for i, c in enumerate(s1):
if c != s2[i]:
ans = s1[:i]
break
for each in range(len(m)):
m[each] = m[each].split(ans, 1)[-1]
return m

关于Python 在整个列表中查找字符串的公共(public)部分并将其从每个项目中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46128615/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com