使用目录中所有可能的文件组合作为python的输入

2024-10-03 09:13:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中有一个程序,它使用两个文件作为输入,并计算它们之间的相似性。我想使用目录中所有可能的文件组合作为输入。如何使用python扩展我已有的脚本来实现这一点?在

我知道有一些工具,比如glob可以遍历整个文件。但是,如何创建所有不同的文件组合?在

同样,作为@hcwhsa和@Ashish Nitin Patil,如何将itertools与{}结合??在

谢谢你的任何见解。在

更多细节:

我的代码需要2个相同的输入(我有大约50个这样的文件的目录)。 每个输入是3个制表符分隔的列(value1、value2、weight)。 基本上,根据这些信息,我计算得到了here的jaccard系数:

def compute_jaccard_index(set_1, set_2):
    return len(set_1.intersection(set_2)) / float(len(set_1.union(set_2))) 

我想计算目录中所有可能的文件组合的系数。 到目前为止,我在本地调用每个文件为:

^{pr2}$

我的目标是在目录中所有可能的文件组合上迭代该函数。在


Tags: 文件工具程序目录脚本len相似性glob
2条回答
import itertools
import os
for file_1, file_2 in itertools.combinations(os.listdir(os.getcwd()), 2):
    print(file_1, file_2)
    # compare the files

os.getcwd()替换为目录路径。在

此代码段比较path中的所有文件。在

import os
from itertools import combinations

path = r'path/to/dir'
entries = os.listdir(path)
filenames = [os.path.join(path, entry) for entry in entries if os.path.isfile(os.path.join(path, entry))]

for (file1, file2) in combinations(filenames, 2):
    with open(file1) as f1, open(file2) as f2:
        # Compare the files

在python3中,它可能会做得更优雅一些。在

^{pr2}$

相关问题 更多 >