簡體   English   中英

需要計算“AGAT”、“AATG”和“TATC”在具有 DNA 序列的 .txt 文件中重復了多少次

[英]Need to count how many times “AGAT” “AATG” and “TATC” repeats in .txt file that has a DNA sequence

這是我的第一個編碼 class 並且每次給定的一個出現在 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 語句。 以及一旦您遍歷文件一次,文件指針就在末尾(我認為),所以它不會 go 回來。 下面的代碼一次遍歷每一行,並將字符串與 4 個字符序列進行比較,請注意.strip()刪除文件遍歷時line變量中的尾隨\n和或\r字符.

通常,在打開文件時,最好使用with open(filename, mode) as 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM