0

我正在尝试编写一个简单的脚本来从 VCF 文件中提取特定数据,该文件显示基因组序列中的变体。

该脚本需要从文件中提取标头以及 SNV,同时省略任何插入删除。变体显示在 2 列中,即 ALT 和 REF。每列由空格分隔。Indels 在 ALT 或 REF 中将有 2 个字符,SNV 将始终有 1 个。

到目前为止,我提取了标题(始终以## 开头),但没有提取任何变体数据。

original_file = open('/home/user/Documents/NA12878.vcf', 'r')
extracted_file = open('NA12878_SNV.txt', 'w+')

for line in original_file:
   if '##' in line:
       extracted_file.write(line)

# Extract SNVs while omitting indels 
# Indels will have multiple entries in the REF or ALT column
# The ALT and REF columns appear at position 4 & 5 respectively

for line in original_file:
    ref = str.split()[3]
    alt = str.split()[4]
    if len(ref) == 1 and len(alt) == 1:
        extracted_file.write(line)

original_file.close()
extracted_file.close()
4

2 回答 2

1
original_file = open('NA12878.vcf', 'r')
extracted_file = open('NA12878_SNV.txt', 'w+')
i=0

for line in original_file:
    if '##' in line:
        extracted_file.write(line)
    else:
        ref = line.split('  ')[3]
        alt = line.split('  ')[4]
        if len(ref) == 1 and len(alt) == 1:
            extracted_file.write(line)

# Extract SNVs while omitting indels 
# Indels will have multiple entries in the REF or ALT column
# The ALT and REF columns appear at position 4 & 5 respectively

original_file.close()
extracted_file.close()

有两个问题:

  1. 第二个循环永远不会执行,因为您已经在第一个循环中到达了 VCF 文件的末尾。您可以在此处查看如何在同一文本文件上重新开始新循环。
  2. 您没有正确分隔线,它是制表符分隔的。

因此,我将代码设置为仅使用一个循环执行并将选项卡放置为拆分参数。

于 2019-02-21T16:29:14.013 回答
0

Adirmola 给出的答案很好,但是您可以通过应用一些修改来提高代码质量:

# Use "with" context managers to open files.
# The closing will be automatic, even in case of problems.
with open("NA12878.vcf", "r") as vcf_file, \
        open("NA12878_SNV.txt", "w") as snv_file:
    for line in vcf_file:
        # Since you have specific knowledge of the format
        # you can be more specific when identifying header lines
        if line[:2] == "##":
            snv_file.write(line)
        else:
            # You can avoid doing the splitting twice
            # with list unpacking (using _ for ignored fields)
            # https://www.python.org/dev/peps/pep-3132/
            [_, _, _, ref, alt, *_] = line.split("\t")  # "\t" represents a tab
            if len(ref) == 1 and len(alt) == 1:
                snv_file.write(line)

我在您的文件上使用 python 3.6 对此进行了测试,最终得到 554 个 SNV。这里使用的一些语法(尤其是列表解包)可能不适用于较旧的 python 版本。

于 2019-02-27T16:32:47.633 回答