如何删除包含相同名称的路径?
How to delete paths that contain the same names?
我有一个看起来像这样的路径列表(见下文)。如您所见,文件命名不一致,但我想每个人只保留一个文件。我已经有一个函数可以删除重复项,如果它们具有完全相同的文件名但文件扩展名不同,但是,对于这种不一致的文件命名情况,它似乎更棘手。
文件列表看起来像这样(但假设有成千上万的路径和单词不是全名的一部分,例如简历、履历等):
all_files =
['cv_bob_johnson.pdf',
'bob_johnson_cv.pdf',
'curriculum_vitae_bob_johnson.pdf',
'cv_lara_kroft_cv.pdf',
'cv_lara_kroft.pdf' ]
期望的输出:
unique_files = ['cv_bob_johnson.pdf', 'cv_lara_kroft.pdf']
考虑到名字在大多数情况下都有些书面形式(例如名字在姓氏之前),我假设如果名字重复,必须有一种方法来获得一组唯一的路径?
如果您想使您的算法相对简单(即不使用 ML 等),您需要了解要删除的典型子字符串。让我们列出这样的子字符串,例如:
remove = ['cv_', '_cv', 'curriculum_vitae_', '_curriculum_vitae']
然后您可以这样处理您的文件列表:
import re
all_files = ['cv_bob_johnson.pdf', 'bob_johnson_cv.pdf', 'curriculum_vitae_bob_johnson.pdf', 'cv_lara_kroft_cv.pdf', 'cv_lara_kroft.pdf']
remove = ['cv_', '_cv', 'curriculum_vitae_', '_curriculum_vitae']
unique = []
for file in all_files:
# strip a suffix, if any:
try:
name, suffix = file.rsplit('.', 1)
except:
name, suffix = file, None
# remove the excess parts:
for rem in remove:
name = re.sub(rem, '', name)
# append the result to the list:
unique.append(f'{name}.{suffix}' if suffix else name)
# remove duplicates:
unique = list(set(unique))
print(unique)
我有一个看起来像这样的路径列表(见下文)。如您所见,文件命名不一致,但我想每个人只保留一个文件。我已经有一个函数可以删除重复项,如果它们具有完全相同的文件名但文件扩展名不同,但是,对于这种不一致的文件命名情况,它似乎更棘手。
文件列表看起来像这样(但假设有成千上万的路径和单词不是全名的一部分,例如简历、履历等):
all_files =
['cv_bob_johnson.pdf',
'bob_johnson_cv.pdf',
'curriculum_vitae_bob_johnson.pdf',
'cv_lara_kroft_cv.pdf',
'cv_lara_kroft.pdf' ]
期望的输出:
unique_files = ['cv_bob_johnson.pdf', 'cv_lara_kroft.pdf']
考虑到名字在大多数情况下都有些书面形式(例如名字在姓氏之前),我假设如果名字重复,必须有一种方法来获得一组唯一的路径?
如果您想使您的算法相对简单(即不使用 ML 等),您需要了解要删除的典型子字符串。让我们列出这样的子字符串,例如:
remove = ['cv_', '_cv', 'curriculum_vitae_', '_curriculum_vitae']
然后您可以这样处理您的文件列表:
import re
all_files = ['cv_bob_johnson.pdf', 'bob_johnson_cv.pdf', 'curriculum_vitae_bob_johnson.pdf', 'cv_lara_kroft_cv.pdf', 'cv_lara_kroft.pdf']
remove = ['cv_', '_cv', 'curriculum_vitae_', '_curriculum_vitae']
unique = []
for file in all_files:
# strip a suffix, if any:
try:
name, suffix = file.rsplit('.', 1)
except:
name, suffix = file, None
# remove the excess parts:
for rem in remove:
name = re.sub(rem, '', name)
# append the result to the list:
unique.append(f'{name}.{suffix}' if suffix else name)
# remove duplicates:
unique = list(set(unique))
print(unique)