0
使用以下脚本,我将3个文件解析为python中的一个字典。字典没有全部类似的键,我希望每个字典的值在我的输出csv文件的新列中显示。因此,键必须全部位于一列中,后面是各包含不同字典值的列。 我的脚本存在的问题是,如果它们存在,那么只会附加值,结果是不同字典的值位于输出csv文件的错误列中。 我的脚本如下:python;将字典与每个字典合并到输出csv文件的新列中
def get_file_values(find_files, output_name):
for root, dirs, files in os.walk(os.getcwd()):
if all(x in files for x in find_files):
outputs = []
for f in find_files:
d = {}
with open(os.path.join(root, f), 'r') as f1:
for line in f1:
ta = line.split()
d[ta[1]] = int(ta[0])
outputs.append(d)
d3 = defaultdict(list)
for k, v in chain(*(d.items() for d in outputs)):
d3[k].append(v)
with open(os.path.join(root, output_name), 'w+', newline='') as fnew:
writer = csv.writer(fnew)
writer.writerow(["genome", "contig", "genes", "SCM", "plasmidgenes"])
for k, v in d3.items():
fnew.write(os.path.basename(root) + ',')
writer.writerow([k] + v)
print(d3)
get_file_values(['genes.faa.genespercontig.csv', 'hmmer.analyze.txt.results.txt', 'genes.fna.blast_dbplasmid.out'], 'output_contigs_SCMgenes.csv')
我现在输出的是:
genome contig genes SCM plasmidgenes
Linda 9 359 295 42
Linda 42 1 2
Linda 73 29 5
Linda 43 17 6
Linda 74 4
Linda 48 11
Linda 66 27
而且我想拥有它喜欢;
genome contig genes SCM plasmidgenes
Linda 9 359 295 42
Linda 42 1 2 0
Linda 73 0 29 5
Linda 43 17 0 6
Linda 74 0 0 4
Linda 48 0 11 0
Linda 66 27 0 0
嘿。你有什么特殊原因需要使用字典吗?因为使用熊猫系列和数据框会更适合这项工作。 – Arthur
我从来没有使用过数据框,但对我来说使用它也很好。你可以给我一些重写熊猫脚本的帮助吗?输入文件与您所期望的完全相反:首先是键值(与空格分隔)。因此,我认为字典将是一个不错的选择。 – Gravel
当然我可以帮忙。但首先,我有一点点麻烦来想象你的输入。你能发布文件1内容只是为了帮助我吗?我猜是这样的: 琳达基因组\ n 9重叠群\ n 359个基因的\ n 295 SCM \ n 42 plasmidgenes的\ n – Arthur