分割一个fasta文件并基于第一个lin重命名

2024-05-14 14:39:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含以下内容的大文件:

文件名:input.txt

>chr1
jdlfnhl
dh,ndh
dnh.

dhjl

>chr2
dhfl
dhl
dh;l

>chr3

shgl
sgl

>chr2_random
dgld

我需要将此文件拆分为四个单独的文件,如下所示:

文件1:chr1.fa

>chr1
jdlfnhl
dh,ndh
dnh.

dhjl

文件2:chr2.fa

>chr2
dhfl
dhl
dh;l

文件3:chr3.fa

>chr3

shgl
sgl

文件4:chr2_random.fa

>chr2_random
dgld

我在linux中尝试了csplit,但无法按“>;”后的文本重命名它们。

csplit -z input.txt '/>/' '{*}'

Tags: 文件txtinputrandomfadhchr1dhl
3条回答

既然你表明你在Linux系统上,那么“awk”似乎是合适的工具。

用法:
./foo.awk your_input_file

foo.awk:

#!/usr/bin/awk -f

/^>chr/ {
    OUT=substr($0,2) ".fa"
}

OUT {
    print >OUT
}

你也可以在一行中这样做:

awk '/^>chr/ {OUT=substr($0,2) ".fa"}; OUT {print >OUT}' your_input

略显凌乱的脚本,但应该能处理大文件,因为它一次只能读取一行

要运行,您需要python thescript.py input.txt(或者它将从stdin读取,比如cat input.txt | python thescript.py

import sys
import fileinput

in_file = False

for line in fileinput.input():
    if line.startswith(">"):
        # Close current file
        if in_file:
            f.close()

        # Make new filename
        fname = line.rstrip().partition(">")[2]
        fname = "%s.fa" % fname

        # Open new file
        f = open(fname, "w")
        in_file = True

        # Write current line
        f.write(line)

    elif in_file:
        # Write line to currently open file
        f.write(line)

    else:
        # Something went wrong, no ">chr1" found yet
        print >>sys.stderr, "Line %r encountered, but no preceeding > line found"

如果你发现自己想用FASTA/FASTQ文件做更复杂的事情,你应该考虑Biopython。

这里有一篇关于修改和重新编写FASTQ文件的文章:http://news.open-bio.org/news/2009/09/biopython-fast-fastq/

还有一个关于拆分FASTA文件的问题:http://lists.open-bio.org/pipermail/biopython/2012-July/008102.html

相关问题 更多 >

    热门问题