我正在通过比较文件名来寻找重复文件。
但是,我发现os.walk
返回的某些路径包含转义字符。例如,我可能会为一个文件获取structure in the Earth\'s core.pdf
而为另一个文件获得structure in the Earth\xe2\x80\x99s core.pdf
。
In [1]: print 'structure in the Earth\'s core.pdf\nstructure in the Earth\xe2\x80\x99s core.pdf'
structure in the Earth's core.pdf
structure in the Earth’s core.pdf
In [2]: 'structure in the Earth\'s core.pdf' == 'structure in the Earth\xe2\x80\x99s core.pdf'
Out[2]: False
我如何处理这些案件?
==== 为了澄清Q以回应评论,还有其他情况下重复文件,如
-
分隔,而另一个文件名由:
答案 0 :(得分:1)
也许你可以得到字符串的相似性而不是完全匹配。由于大写等简单的事情,获得完全匹配可能会有问题。
我建议如下:
from difflib import SequenceMatcher
s1 = "structure in the Earth\'s core.pdf"
s2 = "structure in the Earth\xe2\x80\x99s core.pdf"
matcher = SequenceMatcher()
matcher.set_seqs(s1, s2)
print(matcher.ratio())
# 0.9411764705882353
该结果表明两个字符串之间的相似性超过94%。您可以定义删除阈值或在删除前查看项目。