使用 Python 以成对方式比较文件



我正在尝试比较同一目录中两个文件的内容以匹配行。我想最终以成对的方式做到这一点。现在,我已经编写了一些代码,可以使目录中的第一个文件保持打开状态,并将其与该目录中的其余文件进行比较。我在实现时遇到的是用目录中的第二个文件重复逻辑,然后是第三个文件,依此类推。

我是 Python 的新手,只是使用我迄今为止获得的知识来执行此代码。我正在考虑为第一个文件添加另一个计数器。这样,一旦文件与第一个文件进行比较,file1counter 就会添加一个文件,因此现在 file1read 正在打开 file1read[1] 并重复。

import os
#define path where files to be compared are located
path = ("/path/to/files/")
#lists all files in a directory and sorts them alphabetically
files = sorted(os.listdir( path ))
#count the number of files in the directory
number_files = len(files)
count = 1
#open first file in the directory
file1 = open(path+files[0], 'r')
#store lines of the file 
file1read = file1.read().splitlines() 
#while loop to compare file 1 to file 2, then file 1 to file 3 ... to file n
while (count < number_files):
file2 = open(path+files[count], 'r')
file2read = file2.read().splitlines() 
for i in file1read:
for j in file2read:
if i == j:
print (os.path.basename(file1.name)+"_"+os.path.basename(file2.name)+" have {} in common".format(j))
count = count + 1

您可以使用itertools.combinations来获取目录中所有唯一的文件对,并使用此解决方案来确定文件之间的相似性。此外,glob包具有比os.listdir更好的功能,因为它列出了给定目录中文件的正确路径:

import itertools
import glob
path = ("/path/to/files/")
for files in itertools.combinations(glob.glob(path + '*'), 2):
file1, file2 = map(open, files)
similarities = set(file1).intersection(file2)
if similarities:
print('_'.join(files), 'have {} in common'.format(','.join(similarities))

最新更新