python中的字符串比较

时间:2017-10-06 19:35:58

标签: python string character-encoding char

我正在通过比较文件名来寻找重复文件。

但是,我发现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以回应评论,还有其他情况下重复文件,如

  • 一个文件名包含的空格多于另一个
  • 一个文件名由-分隔,而另一个文件名由:
  • 分隔
  • 一个包含日文/中文单词的文件名,另一个由数字和日文/中文单词组成......

1 个答案:

答案 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%。您可以定义删除阈值或在删除前查看项目。

相关问题