import csv codon_counts = {} with open('D:/QLNU/writing/homework/BI/2022-2023第二学期作业/20230607/hORFeome_V8.1.fasta', 'r') as f: dna_sequence = f.read().replace('\n', '') # count the occurrences of each codon codon_counts = {dna_sequence[i:i+3]: codon_counts.get(dna_sequence[i:i+3], 0) + 1 for i in range(0, len(dna_sequence), 3)} #calculate the total number of codons total_codons = sum(codon_counts.values()) codon_frequencies = {} for codon in codon_counts: codon_frequencies[codon] = codon_counts[codon] / total_codons # write the results to the output file with open('D:/QLNU/writing/homework/BI/2022-2023第二学期作业/20230607/out.CSV', 'w', newline='') as f_out: writer = csv.writer(f_out) writer.writerow(['Codon', 'Frequency']) for codon in codon_frequencies: writer.writerow([codon, codon_frequencies[codon]])优化一下代码,使其读文件时从第二行开始隔行读取
时间: 2024-04-01 14:32:10 浏览: 94
import csv
codon_counts = {}
with open('D:/QLNU/writing/homework/BI/2022-2023第二学期作业/20230607/hORFeome_V8.1.fasta', 'r') as f:
# skip the first line
next(f)
# read every other line
dna_sequence = ''.join(line.strip() for i, line in enumerate(f) if i % 2 == 0)
# count the occurrences of each codon
codon_counts = {dna_sequence[i:i+3]: codon_counts.get(dna_sequence[i:i+3], 0) + 1 for i in range(0, len(dna_sequence), 3)}
# calculate the total number of codons
total_codons = sum(codon_counts.values())
codon_frequencies = {}
for codon in codon_counts:
codon_frequencies[codon] = codon_counts[codon] / total_codons
# write the results to the output file
with open('D:/QLNU/writing/homework/BI/2022-2023第二学期作业/20230607/out.CSV', 'w', newline='') as f_out:
writer = csv.writer(f_out)
writer.writerow(['Codon', 'Frequency'])
for codon in codon_frequencies:
writer.writerow([codon, codon_frequencies[codon]])
阅读全文