Python: 如何在输出中输出正确的染色体名称?

Python: How to output the correct chromosome name in the output?

当我尝试修改染色体名称不跟在输入文件染色体名称后面的代码时,我遇到了这个错误。基本上下面的代码是读取输入文件并通知较短序列的位置,并根据文件中给出的信息输出位置序列。例如在 chr4 中:154742507-154742714,值 151 表示第一碱基的位置,'CCCAGGCTGG' 位置是 173 - 182。因此使用下面的代码应该能够 return 我的确切位置将 173 添加到 154742507 并获得以下输出。谁能帮帮我?

下面是带有示例输入文本文件的代码。

Input.txt

chr4:154742507-154742714


                           CCCAGGCTGG
151  AGTCTTGCTTTTTTTGTCGTTGCCCAGGCTGGAGTGCAGTGGCACCATCTCGGCTCAC


chr9:47303792-47303999

      CCAGCCTGGG
1    TCCAGCCTGGGTGACAGCGTGAGGCTCTTGTCTCAAATAGAAAAAAAACAAAGAACAAAAAACAAAAAACCACCA

输出

chr1    154742680   154742690
chr1    47303794    47303804

预期输出

chr4    154742680   154742690
chr9    47303794    47303804

代码

import re  # regular expressions, not needed (alternatives: the `split` method) but convenient

result = []
output_file=open('output.bed','w')
with open('Input.txt') as f:
    for line in f:
        if line.startswith('chr'):
            label = line.strip()
        elif line[0] == ' ':
            # short sequence
            length = len(line.strip())
            # find the index of the beginning of the short sequence
            for i, c in enumerate(line):
                if c.isalpha():
                    short_index = i
                    break
        elif line[0].isdigit():
            # long sequence
            n = line.split(' ')[0]
            # find the index of the beginning of the long sequence
            for i, c in enumerate(line):
                if c.isalpha():
                    long_index = i
                    break
            start = int(n) + short_index - long_index
            start -= 1
            end = start + length
            result.append('{} {} {}'.format(label, start, end))
            offset, n, start, length = 0, 0, 0, 0
output_line= "\n".join(result)
output_file.write(output_line)
output_file.close()

output_file=open('last_output.bed','w')
with open('output.bed') as fin:
    for line in fin:
        start, _, offset_start, offset_end = re.search(r'[^:]*:(\d+)\D+(\d+)\D+(\d+)\D+(\d+)', line).groups()
        output_line=('chr1\t{}\t{}\n'.format(int(start) + int(offset_start) + 1,int(start) + int(offset_end) + 1))
        output_file.write(output_line)
output_file.close()

如果我没看错的话,你遇到的问题只与输出错误的染色体数目(chr##)有关。

这似乎有点明显。在代码的末尾,您正在对其进行硬编码:

output_line=('chr1\t{}\t{}\n'.format(stuff))

如果您不希望输出始终显示 chr1,则需要对其进行更改。

上一行的正则表达式似乎与文件中的染色体编号相匹配,您只是没有将其捕获到稍后可以使用的组中。尝试:

chromosome, start, _, offset_start, offset_end = re.search(r'([^:]*):(\d+)\D+(\d+)\D+(\d+)\D+(\d+)', line).groups()
output_line=('{}\t{}\t{}\n'.format(chromosome, int(start) + int(offset_start) + 1,int(start) + int(offset_end) + 1))

这仍然很丑陋,但应该可以。请注意,如果您从初始循环中获得正确的输出,而不是写出中间格式然后需要重新解析它,将会容易得多。