Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/19.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 需要计算多少次;“阿加特”&引用;AATG“;及;“TATC”;在具有DNA序列的.txt文件中重复_Python_Counter_Dna Sequence - Fatal编程技术网

Python 需要计算多少次;“阿加特”&引用;AATG“;及;“TATC”;在具有DNA序列的.txt文件中重复

Python 需要计算多少次;“阿加特”&引用;AATG“;及;“TATC”;在具有DNA序列的.txt文件中重复,python,counter,dna-sequence,Python,Counter,Dna Sequence,这是我的第一个编码类,每次DNA序列中出现一个给定值时,我都很难让计数器增加 到目前为止,我的代码是: agat_Counter = 0 aatg_Counter= 0 tatc_Counter= 0 DNAsample = open('DNA SEQUENCE FILE.txt', 'r'); for lines in DNAsample: if lines in DNAsample=='AGAT': agat_Counter+=1 else:

这是我的第一个编码类,每次DNA序列中出现一个给定值时,我都很难让计数器增加

到目前为止,我的代码是:

agat_Counter = 0
aatg_Counter= 0
tatc_Counter= 0
DNAsample = open('DNA SEQUENCE FILE.txt', 'r');
for lines in DNAsample:
    if lines in DNAsample=='AGAT':
        agat_Counter+=1
    else:
        agat_Counter+=0
print(agat_Counter)
    
for lines in DNAsample:
    if lines in DNAsample=='AATG':
        aatg_Counter+=1
    else:
        aatg_Counter+=0
print(aatg_Counter)
for lines in DNAsample:
    if lines in DNAsample=='TATC':
        tatc_Counter+=0
    else:
        tatc_Counter+=0
print(tatc_Counter)

你可以用很多方法做到这一点。其中一个更简单的方法是:

DNAsample = open('DNA SEQUENCE FILE.txt', 'r').read()
agat_Counter = DNAsample.count('AGAT')
aatg_Counter= DNAsample.count('AATG')
tatc_Counter= DNAsample.count('TATC')

这应该行得通。问题在于你的if语句。正如您迭代一次文件一样,文件指针位于末尾(我认为),因此它不会返回。下面的代码一次遍历一行,并将字符串与4个字符的序列进行比较,请注意,
.strip()
在文件遍历时删除
\n
和/或
\r
变量中的尾随
字符

通常,在打开文件时,最好使用
并将open(filename,mode)作为var:
,如下所示,这样可以在完成后关闭文件,并消除未关闭文件句柄的风险

基于原始代码的假设是
DNA SEQUENCE FILE.txt
文件组织如下:

AGAT
AATG
...

为什么不使用内置的?这是作业吗?输入文件是什么样子的?它们都在一行还是一长串文本?
agat_Counter = 0
aatg_Counter= 0
tatc_Counter= 0

with open('DNA SEQUENCE FILE.txt', 'r') as DNAample:
    for line in DNAsample:
        strippedLine = line.strip()
        if strippedLine == 'AGAT':
            agat_Counter += 1
        elif strippedLine == 'AATG':
            aatg_Counter += 1   
        elif stripepdLine == 'TATC':
            tatc_Counter += 1

print(agat_Counter)
print(aatg_Counter)
print(tatc_Counter)