【问题标题】:Extracting gene sequences from FASTA File?从 FASTA 文件中提取基因序列?
【发布时间】:2019-02-08 05:48:23
【问题描述】:

我有以下代码,它读取包含 10 个基因序列的 FASTA 文件,并将每个序列作为矩阵返回。 然而,最后一个序列中的代码似乎丢失了,我想知道为什么?

file=open('/Users/vivianspro/Downloads/rosalind_cons (5).txt', 'r')
line=file.readline()

strings = []
sequence=''
while line:
    #line=line.rstrip('\n')
    line = line.strip() #empty () automatically strips the \n
    if '>' in line:
        if sequence != "":
            strings.append(sequence)
            sequence = ""
        #sequence=line
    else:
        sequence+=line
    line=file.readline()
for s in strings:
    print(s)

Motifs = []
for seq in strings:
    Motifs.append(list(seq))

#make every symbol into an element in the list separated by ,
for s in Motifs:
    print(s) ````


【问题讨论】:

  • 如果 '>' 在行中,您只能附加到字符串。我们可以看看一些示例数据吗?
  • @AustinHastings 这就是 FASTA 的格式。通过查找格式很容易看到一些样本,例如在维基百科上。

标签: python bioinformatics biopython fasta


【解决方案1】:

当你看到一个新的> 但在最后一个序列之后没有一个时,你只会追加到strings

这是一个重构,希望它也更符合习惯。

strings = []
sequence=''

with open('/Users/vivianspro/Downloads/rosalind_cons (5).txt', 'r') as file:
    for line in file:
        line = line.rstrip('\n')
        if line.startswith('>'):
            if sequence != "":
                strings.append(sequence)
            sequence = ""
        else:
            sequence+=line
    # After the last iteration, append once more if we have something to append
    if sequence:
        strings.append(sequence)

【讨论】:

    【解决方案2】:

    由于 FASTA 文件包含这种格式的数据:

    >ID1
    seq_1
    >ID2
    seq_2
    ...
    

    根据您的代码,如果您的行仅包含 >,则您尝试附加该序列。这意味着,当您迭代 ID_2 时,您正在添加 ID_1 的序列。

    要解决此问题,您可以执行以下操作:

    for line in file:
        line = line.strip()
        if '>' in line: # Line 1
            line = file.readline().strip()
            # print(line)
            strings.append(line)
    

    上面的示例使用了这样一个事实,即在 FASTA 文件中,序列直接位于 ID 之后,其中包含 > 字符(您可以更改第 1 行,使其仅检查第一个字符 line[0] == ">" )。

    【讨论】:

      猜你喜欢
      • 2018-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-03
      • 1970-01-01
      相关资源
      最近更新 更多