Python:如何比较来自 fasta 文件的多个序列?

标签 python for-loop biopython fasta

我是 python 编程世界的新手,我正在尝试编写一个脚本,给定一个 FASTA 文件,将相互比较序列并对它们进行评分(如果序列 A 中核苷酸的位置匹配如果核苷酸位于序列 B 的相同位置,则得分会上升 2)。到目前为止,我得到了这个:

from Bio import SeqIO


def sequence_compare(file):
    seq_records = SeqIO.parse(file, "fasta") 
    for record in seq_records:
        len1 = len(str(record.seq))
        sequence1 = str(record.seq)
        print(sequence1)
        for record in seq_records:
            len2= len(str(record.seq))
            sequence2 = str(record.seq)
            print(sequence2)
            a = 0
            for pos in range (0,min(len1,len2)) :
                if sequence1[pos] == sequence2[pos]:
                    a+= 2
                if sequence1[pos] != sequence2[pos]:
                    a+= -1
                if sequence1[pos] == sequence2[pos] == '-':
                    a+= -2
            print(a)

它为包含 3 个序列的 Fasta 文件提供的输出:

ACTGACTGACTGACTGACTG
ACTGACTGACTG-ACTGACT
16
AAAAAAAAAAAAAAAAAAAAAAAAAAAAA
-5

在我看来,第一个 for 循环只循环一次,第二个 for 循环不从第一个序列开始。

期望的输出是将每个序列相互比较并评分。所以序列 1 与序列 1 及其得分进行比较,序列 1 与序列 2 及其得分进行比较,序列 1 与序列 3 及其得分进行比较,等等......

如果有人能帮助我,那将不胜感激!

最佳答案

您的代码不起作用的原因是您对内部循环和外部循环使用了相同的循环变量 record。您可能希望将其分别更改为 record1record2

但更好的是,python 支持在 itertools.combinations() 中进行成对组合。 ,这样您就可以避免嵌套循环。

此外,最好将您的评分算法移动到一个单独的函数中。

考虑到以上两个变化,这里是代码:

from Bio import SeqIO
from itertools import combinations


def score(sequence1, sequence2):
    a = 0
    for pos in range(0, min(len(sequence1), len(sequence2))):
        if sequence1[pos] == sequence2[pos]:
            a += 2
        if sequence1[pos] != sequence2[pos]:
            a += -1
        if sequence1[pos] == sequence2[pos] == '-':
            a += -2
    return a


def sequence_compare(file):
    seq_records = SeqIO.parse(file, "fasta")
    for record1, record2 in combinations(seq_records, 2):
        sequence1 = record1.seq
        sequence2 = record2.seq
        a = score(sequence1, sequence2)
        print(sequence1)
        print(sequence2)
        print(a)

关于Python:如何比较来自 fasta 文件的多个序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41044679/

相关文章:

python - 使用正则表达式以任意顺序匹配两个单词

Python : how to stop a thread that's waiting for a . recv()

r - 将循环输出存储在 R 中的数据帧中

java - 比较两个数组中的每个元素

python - 多进程,多个进程读取同一个文件

python - Python中的素数生成器

python - 在 Python 中按顺序获取实例变量

python - while 循环 vs for 循环求 3 和 5 的倍数之和小于 1000

python - 如何计算具有多种模型/构象的蛋白质的平均结构

python - 从fasta文件中有选择地选择核苷酸序列?