以前在华大记得有一个同事是让我用Perl写过一次,如今Perl放下一段时间了,还是用Python写吧~
目的:
根据第一列的值,将多个对应的第2、3、4列的内容分别进行整合,以分号分隔
思路(仅以第二列进行说明)
-
遍历每行,提取第一列和第二列
-
第一列作为唯一索引key,构建字典。
-
如果该字典第一次出现该key,则字典的值为第二列值构造出的列表(只有一个值)
-
遍历字典,格式构造,输出文件
#!/usr/bin/env python
#encoding:utf-8
# catch all column2 data into 1 cell by unique column1
#Author Robin 2020/01/18
temp2 = dict()
temp3 = dict()
temp4 = dict()
with open("/share/nas1/Data/luohb/rawdata.mouse.tsv") as f:
for line in f:
line = line.strip('\n')
key, col2, col3, col4 = line.split("\t")
if key in temp2:
temp2[key].append(col2)
else:
temp2[key] = [col2]
if key in temp3:
temp3[key].append(col3)
else:
temp3[key] = [col3]
if key in temp4:
temp4[key].append(col4)
else:
temp4[key] = [col4]
with open("./new_trrust_rawdata.mouse.tsv", 'w') as f:
for key in temp2:
col2 = ';'.join(temp2[key])
col3 = ';'.join(temp3[key])
col4 = ';'.join(temp4[key])
line = "%s\t%s\t%s\t%s\n" % (key, col2, col3, col4)
f.writelines(line)