Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:读取文件和计算DNA质量_Python_File_Mass - Fatal编程技术网

Python:读取文件和计算DNA质量

Python:读取文件和计算DNA质量,python,file,mass,Python,File,Mass,我在创建读取文件并使用以下细节计算该文件DNA质量的代码时遇到问题:a=313.2 C=289.2 G=329.2 T=304.2 结果是这样的: ACCGAA=1847.2 代码还需要将结果保存在新文件中 这个文件只是一个.txt文件,里面有一个dna字符串,比如:ACCGTACGT我想这会让你开始。 它的作用是读取dna.txt文件,并将txt文件中的文本保存到dna 然后对每个字符检查是否等于特定字符,如果等于,则将值添加到总数中。对文件中的所有字符执行此操作 with open('dna

我在创建读取文件并使用以下细节计算该文件DNA质量的代码时遇到问题:a=313.2 C=289.2 G=329.2 T=304.2

结果是这样的: ACCGAA=1847.2

代码还需要将结果保存在新文件中


这个文件只是一个.txt文件,里面有一个dna字符串,比如:ACCGTACGT

我想这会让你开始。 它的作用是读取
dna.txt
文件,并将txt文件中的文本保存到
dna

然后对每个字符检查是否等于特定字符,如果等于,则将值添加到总数中。对文件中的所有字符执行此操作

with open('dna.txt', 'r') as f:
    dna = f.read()

total = 0
for each in dna:
    if each == "A":
        total = total + 313.2
    elif each == "C":
        total  = total + 289.2
    elif each == "G":
        total  = total + 329.2
    elif each == "T":
        total  = total + 304.2

file = open('output.txt', 'w')
file.write(str(total))
file.close()

如果您对@mtkilic中更具Python风格的方式感兴趣,可以尝试以下方法:

dna = open('dna.txt', 'r').read()
d = {'A':313.2, 'C':289.2, 'G':329.2, 'T':304.2}
total = sum([d.get(each, 0.0) for each in dna])
file = open('output.txt', 'w')
file.write(str(total))
file.close()

我们使用dict存储每个成分的DNA质量,然后用列表计算总和。我们使用
get
方法访问键值。如果无法从字典键识别字符,它允许返回0.0质量。

到目前为止,您尝试了什么?你的文件是什么格式的?文件中的数据是什么样子的?它只是一个包含dna的txt文件,没有什么特别的,我真的不知道如何创建新文件并将结果保存在其中
file=open(“testfile.txt”,“w”)
这将为您创建testfile.txt
file.write(“Hello World”)
file.close()
如果您有任何问题,请告诉我