我有一个带有DNA序列的Fasta文件,我想对每个DNA序列进行配对比较。
fasta文件包含这样的形式。
>dna1
TAGTACTGACCATGGCGTTTGTTG
>dna2
ACCTTGAGATACAAAACGATTGGACTG
>dna3
GCTTCACTGATGCAGTATTCAATTAACCAG
>dna4
CCACTGGAGCTTTCCAAAGGG
>dna5
TCTGTGGGTCCGGTTGTACAG
我的方法是先从DNA序列的快速文件中建立一个字典 然后对字典中的值进行一对一的比较 找出每对序列之间的%age identity!
我在做配对比较的时候遇到了问题!
我的代码如下。
from collections import OrderedDict
from typing import Dict
# Convert the fasta file to dictionary
DnaName_SYMBOL = '>'
def parse_DNAsequences(filename: str,
ordered: bool=False) -> Dict[str, str]:
# filename: str is the DNA sequence name
# ordered: bool, Gives us an option to order the resulting dictionary
result = OrderedDict() if ordered else {}
last_name = None
with open(filename) as sequences:
for line in sequences:
if line.startswith(DnaName_SYMBOL):
last_name = line[1:-1]
result[last_name] = []
else:
result[last_name].append(line[:-1])
for name in result:
result[name] = ''.join(result[name])
return result
DNAdict = parse_DNAsequences('output.fas')
这部分是我的问题所在,在字典中迭代值。
def PairwiseComparison():
match = sum(s1 == s2 for s1, s2 in zip(a,b))
if len(s1) > len(s2):
lengthchosen = len(s1)
percentidentity = 100*match/lengthchosen
print('{} vs {} {}%').format(percentidentity)
输出结果应该是这样的
dna1 vs dna2 90%
dna1 vs dna3 100%
dna2 vs dna3 90%
其他说明 如果我们比较2个DNA序列,其中一个的长度大于另一个,那么我们就用这个长度来计算。身份百分比 二者之间
我想,你成功地创建了DNA的字典,我已经在我的例子上硬编码了。itertools.combinations
from itertools import combinations
dna_dict = {
'dna1': 'TAGTACTGACCATGGCGTTTGTTG',
'dna2': 'ACCTTGAGATACAAAACGATTGGACTG',
'dna3': 'GCTTCACTGATGCAGTATTCAATTAACCAG'
}
def PairwiseComparison(d1, d2):
match = sum(s1 == s2 for s1, s2 in zip(d1,d2))
if len(d1) > len(d2):
lengthchosen = len(d1)
else:
lengthchosen = len(d2)
percentidentity = 100*match/lengthchosen
return percentidentity
# Creates all the possible combinations of the dictionary keys
dna_combinations = combinations(dna_dict, 2)
for dna1, dna2 in dna_combinations:
percent_identity = PairwiseComparison(dna_dict[dna1], dna_dict[dna2])
print(f'{dna1} vs {dna2} {percent_identity}%') # The f-strings need python > 3.6, you can change the format if you have a lower version
如果你需要任何澄清和补充,请随时添加评论。