我的问题是这个.我有一个文件有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个被比较文件的行.这是我关心的问题……
最佳答案 我找到了一个似乎在很长一段时间内工作的解决方案.代码如下:
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分钟内计算出这个数据集.当然,还有改进的方法.一个想法是花时间和数据集进行排序,以后稍后搜索会更快,我们可以节省时间!