比较python

时间:2016-11-08 13:35:58

标签: python

我的问题是这个。我有一个文件有3000行和8列(空格分隔)。重要的是第一列是1到22之间的数字。因此,在“分而治之”原则中,我根据第一列值将原始文件拆分为22个子文件。

我有一些结果文件。其中15个源包含1个结果文件。但是结果文件太大了,所以我再次应用了“分而治之”来将15个结果中的每一个分成22个子文件。

文件结构如下:

Original_file                Studies
    split_1                      study1
                                     split_1, split_2, ...
    split_2                      study2
                                     split_1, split_2, ...
    split_3                      ...
    ...                          study15
                                     split_1, split_2, ...
    split_22

因此,通过这样做,我们在开始时支付了一点点开销,但所有这些拆分文件将在最后删除。所以它并不重要。

我需要将我的最终输出作为原始文件,其中包含附加研究的一些值。

所以,到目前为止我的观点是:

Algorithm:
    for i in range(1,22):
        for j in range(1,15)
            compare (split_i of original file) with the jth studys split_i
            if one value on a specific column matches:
                create a list with needed columns from both files, split row with ' '.join(list) and write the result in outfile.

有没有更好的方法来解决这个问题?因为研究文件的大小从300MB到1.5GB不等。

到目前为止,这是我的Python代码:

folders = ['study1', 'study2', ..., 'study15']
with open("Effects_final.txt", "w") as outfile:
    for i in range(1, 23):
        chr = i
        small_file = "split_"+str(chr)+".txt"
        with open(small_file, 'r') as sf:
            for sline in sf: #small_files
                sf_parts = sline.split(' ')
                for f in folders:
                    file_to_compare_with = f + "split_" + str(chr) + ".txt"
                    with open(file_to_compare_with, 'r') as cf: #comparison files
                        for cline in cf:
                            cf_parts = cline.split(' ')
                            if cf_parts[0] == sf_parts[1]:
                               to_write = ' '.join(cf_parts+sf_parts) 
                               outfile.write(to_write)

但是这段代码使用4个循环,这是一种过度杀伤,但是你必须这样做,因为你需要同时读取被比较的2个文件中的行。这是我关心的问题......

1 个答案:

答案 0 :(得分:1)

我发现一个解决方案似乎在很长一段时间内都有效。代码如下:

with open("output_file", 'w') as outfile:
    for i in range(1,23):
        dict1 = {}  # use a dictionary to map values from the inital file
        with open("split_i", 'r') as split:
            next(split) #skip the header
            line_list = line.split(delimiter)
            for line in split:
                dict1[line_list[whatever_key_u_use_as_id]] = line_list

            compare_dict = {}
            for f in folders:
                with open("each folder", 'r') as comp:
                    next(comp) #skip the header
                    for cline in comp:
                        cparts = cline.split('delimiter')
                        compare_dict[cparts[whatever_key_u_use_as_id]] = cparts
            for key in dict1:
                if key in compare_dict:
                    outfile.write("write your data")
outfile.close()

通过这种方法,我能够在~10分钟内计算出这个数据集。当然,还有改进的方法。一个想法是花时间对数据集进行排序,以便稍后搜索会更快,我们可以节省时间!

相关问题