如何保存类似python的ts的输出

2024-05-09 21:02:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用biopython包,我想把结果保存为tsv文件。从打印输出到tsv。

for record in SeqIO.parse("/home/fil/Desktop/420_2_03_074.fastq", "fastq"):
    print ("%s %s %s" % (record.id,record.seq, record.format("qual")))

谢谢你。


Tags: 文件inidhomefortsvparserecord
3条回答

我的首选解决方案是使用CSV模块。这是一个标准模块,所以:

  • 其他人已经做了所有的重担。
  • 它允许您利用CSV模块的所有功能。
  • 你可以相当自信它会按预期运行(我自己写的时候并不总是这样)。
  • 你不必重新发明轮子,无论是在你写文件的时候,还是在你在另一端读回它的时候(我不知道你的记录格式,但是如果你的一个记录包含一个选项卡,那么CSV将为你正确地转义它)。
  • 当你离开公司5年后,下一个人必须进去更新代码时,支持会更容易。

下面的代码片段应该可以帮您实现这一点:

#! /bin/env python3
import csv
with open('records.tsv', 'w') as tsvfile:
    writer = csv.writer(tsvfile, delimiter='\t', newline='\n')
    for record in SeqIO.parse("/home/fil/Desktop/420_2_03_074.fastq", "fastq"):
        writer.writerow([record.id, record.seq, record.format("qual")])

注意,这是针对Python 3.x的。如果您使用的是2.x,那么openwriter = ...将略有不同。

如果要使用.tsv在TensorBoard中标记单词嵌入,请使用以下代码片段。它使用CSV模块(请参见Doug's answer)。

# /bin/env python3
import csv

def save_vocabulary():
    label_file = "word2context/labels.tsv"
    with open(label_file, 'w', encoding='utf8', newline='') as tsv_file:
        tsv_writer = csv.writer(tsv_file, delimiter='\t', lineterminator='\n')
        tsv_writer.writerow(["Word", "Count"])
        for word, count in word_count:
            tsv_writer.writerow([word, count])

word_count是这样的元组列表:

[('the', 222594), ('to', 61479), ('in', 52540), ('of', 48064) ... ]

这是相当简单的,而不是打印它,你需要写一个文件。

with open("records.tsv", "w") as record_file:
    for record in SeqIO.parse("/home/fil/Desktop/420_2_03_074.fastq", "fastq"):
        record_file.write("%s %s %s\n" % (record.id,record.seq, record.format("qual")))

如果要命名文件中的各个列,则可以使用:

record_file.write("Record_Id    Record_Seq    Record_Qal\n")

所以完整的代码可能看起来像:

with open("records.tsv", "w") as record_file:
    record_file.write("Record_Id    Record_Seq    Record_Qal\n")
    for record in SeqIO.parse("/home/fil/Desktop/420_2_03_074.fastq", "fastq"):
        record_file.write(str(record.id)+"  "+str(record.seq)+"  "+ str(record.format("qual"))+"\n")

相关问题 更多 >