gpt4 book ai didi

python - 根据内容对同一目录中的文件进行分组

转载 作者:行者123 更新时间:2023-12-01 09:24:10 26 4
gpt4 key购买 nike

我有一个关于对具有相同内容但文件名不同的文件进行分组的问题。我查看了 filecmp.cmp(),但一次只比较两个文件。

这个想法是这样的:

file1: [a,b,c,d,e,f,g,h,i]
file2: [a,b,c,d,e,f,g,h,i]
file3: [a,b,c,d,e,f,g,h,i]
file4: [a,b,c,d,e,f,g,h]
file5: [a,b,c,d,e,f,g,h]
file6: [a,b,c,d,e]

进入:

file(1,2,3): [a,b,c,d,e,f,g,h,i]
file(4,5): [a,b,c,d,e,f,g,h]
file(6): [a,b,c,d,e]

我认为我有大约 1800 个 .txt 文件,但只有大约 20 个唯一文件。我想创建一个列表、字典或显示分组的数据框。

感谢任何帮助。谢谢!

最佳答案

您可以使用 SHA-1 等哈希函数来检查具有相同内容的文件,以下是此 source 的摘录:

import hashlib
BLOCKSIZE = 65536

def hash_value_for(file_name):
hasher = hashlib.sha1()
with open(file_name, 'rb') as afile:
buf = afile.read(BLOCKSIZE)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(BLOCKSIZE)

return hasher.hexdigest()

例如,上面的函数,给定一个文件名,将返回其内容的哈希值。

file1.txt

This is a test.

file2.txt

This is a test!

file3.txt

This is a test.

输出:

print(hash_value_for("file1.txt"))
> 0828324174b10cc867b7255a84a8155cf89e1b8b
print(hash_value_for("file2.txt"))
> cc4bc53ee478380f385721b45247107338a9cec3
print(hash_value_for("file3.txt"))
> 0828324174b10cc867b7255a84a8155cf89e1b8b

现在回到原来的例子:

文件:

假设我们有以下文件,每个文件包含以下内容:

file1: [a,b,c,d,e,f,g,h,i]
file2: [a,b,c,d,e,f,g,h,i]
file3: [a,b,c,d,e,f,g,h,i]
file4: [a,b,c,d,e,f,g,h]
file5: [a,b,c,d,e,f,g,h]
file6: [a,b,c,d,e]

代码:

import hashlib
import itertools

BLOCKSIZE = 65536


def hash_value_for(file_name):
hasher = hashlib.sha1()
with open(file_name, 'rb') as afile:
buf = afile.read(BLOCKSIZE)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(BLOCKSIZE)

return hasher.hexdigest()


file_names = ["file1.txt", "file2.txt", "file3.txt",
"file4.txt", "file5.txt", "file6.txt"]

file_names_with_hash_values = {}
for file_name in file_names:
file_names_with_hash_values[file_name] = hash_value_for(file_name)

result = {}
for key, value in sorted(file_names_with_hash_values.items()):
result.setdefault(value, []).append(key)

print(result)

输出:

{'e99a894b164a9274e7dabc1b77b41f4148860d96': ['file1.txt', 'file2.txt', 'file3.txt'], 
'bf141159c6499f26f46c7bdc28914417ff66aa15': ['file4.txt', 'file5.txt'],
'a019bdc760a550cdc55de1343d4ebbcff1ba49c3': ['file6.txt']}

这只是一个示例,您可以更改代码以满足您的需求(并获得所需的输出)。

关于python - 根据内容对同一目录中的文件进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50573900/

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