根据特定列的 len() 提取文本行

Extracting lines of text depending on the len() of a particular column

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

脚本需要从文件中提取 header 以及 SNV,同时省略任何插入缺失。变体显示在 2 列中,即 ALT 和 REF。每列由白色分隔 space。 Indels 在 ALT 或 REF 中有 2 个字符,SNVs 总是有 1 个字符。

到目前为止,我提取的是 headers(总是以 ## 开头),但没有提取任何变体数据。

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()
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. 您没有正确分隔行,它是制表符分隔的。

所以我将代码设置为只执行一个循环并将制表符作为拆分参数。

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 版本。