【发布时间】:2017-09-15 11:04:05
【问题描述】:
使用以下脚本,我将 3 个文件解析为 Python 中的一个字典。字典没有所有相似的键,我希望输出 csv 文件的新列中的每个字典的值。因此,键必须全部在一列中,然后是每列包含不同字典的值的列。 我的脚本的问题是仅在存在值时才附加值,结果是不同字典的值被放置在输出 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
【问题讨论】:
-
嘿。您是否必须出于某些特定原因使用字典?因为使用 pandas Series 和 Dataframes 会更适合这项工作。
-
我从未使用过数据框,但我也可以使用它。你能帮我重写熊猫的脚本吗?输入文件与您期望的相反:首先是值,然后是键(用空格分隔)。因此,我认为字典会是一个不错的选择。
-
我当然可以帮忙。但首先,我在可视化您的输入时遇到了一些麻烦。您可以发布文件 1 的内容来帮助我吗?我猜是这样的:Linda 基因组 \n 9 contig \n 359 个基因 \n 295 SCM \n 42 个质粒基因 \n
-
我已经在一个新问题中发布了我拥有和需要的内容,因为在那里我可以显示我的文件等。新问题是; stackoverflow.com/questions/43738909/…
标签: python csv dictionary append