首页 > 解决方案 > 在python中保存cvs文件

问题描述

我无法将数据保存到 csv 文件中。我试图将这个基因中的氨基酸分成四组非极性(np)、极性(p)、阴性(neg)和阳性(pos)。我已经弄清楚如何计算所有单个氨基酸并将它们保存到 cvs 文件中,但无法弄清楚如何以与单个氨基酸相同的方式保存来自四组的数据。

这是保存到 csv 中的单个氨基酸的代码:

from Bio import Entrez, SeqIO

Entrez.email = ""

handle = Entrez.efetch(db="nucleotide", id="KT191142", rettype="gb", retmode="text")
record = SeqIO.read(handle, "genbank")
handle.close()

protein_seq = record.seq.translate()
print(protein_seq)

def count_aa(seq, csv_file):

aa_dict = {} # dictionary to store amino acid counts

for aa in seq:

    if aa in aa_dict:
        aa_dict[aa] += 1 # increment the count of an amino acid by 1
    else:
        aa_dict[aa] = 1 # set the count of an amino acid to 1

with open(csv_file, "w") as file:

    aa_list=sorted(aa_dict.keys())

    file.write("amino_acid,count\n")

    for aa in aa_list:
        line = str(aa) + ',' + str(aa_dict[aa]) + '\n'

        file.write(line)

count_aa(protein_seq, "ebola_aa_count2.csv")`

我想将这个新代码保存到一个 csv 文件中,就像之前的代码一样,这里是新代码:

import re

handle = Entrez.efetch(db="nucleotide", id="KT191142", rettype="gb", retmode="text")
records = SeqIO.read(handle, "genbank")
handle.close()

protein_seq = records.seq.translate()
print(protein_seq)

np_count = 0
p_count = 0
neg_count = 0
pos_count = 0

for aa in protein_seq:
    match_np = re.search(r"G|A|V|C|P|L|I|M|W|F", str(aa))
    match_p = re.search(r"S|T|Y|N|Q", str(aa))
    match_neg = re.search(r"D|E", str(aa))
    match_pos = re.search(r"K|R|H", str(aa))
    if match_np:
        np_count += 1
    if match_p:
        p_count += 1
    if match_neg:
        neg_count += 1
    if match_pos:
        pos_count += 1

handle.close()
print(np_count, p_count, neg_count, pos_count)

提前感谢您的帮助!

标签: pythoncsvsavebiopython

解决方案


您绝对应该使用pandas来操作 csv 文件。

import pandas as pd
df = pd.DataFrame(columns = ['np_count', 'p_count', 'neg_count', 'pos_count'], data =[np_count, p_count, neg_count, pos_count])
df.to_csv('output.csv')

推荐阅读