基于某些模式和内存中的信息拆分文件

2024-09-24 02:13:48 发布

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

我正在处理很多这种结构的文件:

BEGIN
TITLE=id=PRD000012;PRIDE_Exp_Complete_Ac_1645.xml;spectrum=1393
PEPMASS=946.3980102539062
CHARGE=3.0+
USER03=
SEQ=DDDIAAL
TAXONOMY=9606
272.228 126847.000
273.252 33795.000
END
BEGIN IONS
TITLE=id=PRD000012;PRIDE_Exp_Complete_Ac_1645.xml;spectrum=1383
PEPMASS=911.3920288085938
CHARGE=2.0+
USER03=
SEQ=QGKFEAAETLEEAAMR
TAXONOMY=9606
1394.637    71404.000
1411.668    122728.000
END
BEGIN IONS
TITLE=id=PRD000012;PRIDE_Exp_Complete_Ac_1645.xml;spectrum=2965
PEPMASS=946.3900146484375
CHARGE=3.0+
TAXONOMY=9606
1564.717    92354.000
1677.738    33865.000
END

这个结构被重复了几千次,但是里面有不同的数据。如您所见,在一些begin-end之间,有时SEQ和USER03不存在。这是因为蛋白质没有被鉴定出来。。。我的问题来了。你知道吗

我想知道有多少蛋白质被鉴定,有多少还未被鉴定。为此,我决定使用bash,因为它更容易管理文件。你知道吗

for i in $(ls *.txt ); do
    echo $i

    awk '/^BEGIN/{n++;w=1} n&&w{print > "./cache/out" n ".txt"} /^END/{w=0}' $i

done

我在这里找到这个(Split a file into multiple files based on a pattern and name the new files by the search pattern in Unix?

然后使用输出并对其进行分类:

for i in $(ls cache/*.txt ); do
    echo $i

    if grep -q 'SEQ' $i; then
        mv $i ./archive_identified
    else
        mv $i ./archive_unidentified
    fi
done

在此之后,我想从分类文件中获取一些数据(例如:spectrum、USER03、SEQ、TAXONOMY)。你知道吗

for i in $( ls archive_identified/*.txt ); do
    echo $i
    grep 'SEQ' $i | cut -d "=" -f2- | tr ',' '\n' >> ./sequences_ide.txt
    grep 'TAXONOMY' $i | cut -d "=" -f2- | tr ',' '\n' >> ./taxonomy_ide.txt
    grep 'USER' $i | cut -d "=" -f2- >> ./modifications_ide.txt
    grep 'TITLE' $i | sed 's/^.*\(spectrum.*\)/\1/g' | cut -d "=" -f2-  >> ./spectrum.txt

done

for i in $( ls archive_unidentified/*.txt ); do
    echo $i
    grep 'TAXONOMY' $i | cut -d "=" -f2- | tr ',' '\n' >> ./taxonomy_unide.txt
    grep 'TITLE' $i | sed 's/^.*\(spectrum.*\)/\1/g' | cut -d "=" -f2-  >> ./spectrum_unide.txt

done

问题是脚本的第一部分花费了太多的时间(我7天前在LSF中运行了脚本,但它仍然在运行),因为数据太大(每个文件12-15gb),生成了上千个文件。在Python或Perl中有什么方法可以做到这一点吗?你知道吗


Tags: 文件intxtfortitlelsgrepseq
1条回答
网友
1楼 · 发布于 2024-09-24 02:13:48

根据您的评论:“我想要一个只有SEQ的文本块的文件和另一个没有SEQ的文本块的文件”

在Perl中,我会这样做:

#!/usr/bin/env perl

use strict;
use warnings;

open ( my $has_seq, '>', 'SEQ' ) or die $!;
open ( my $no_seq, '>', 'NO_SEQ' ) or die $!;
my $seq_count = 0;
my $no_seq_count = 0;

local $/ = 'END'; 

#iterate stdin or files specified on command line, just like sed/grep
while ( <> ) {
    #check if this chunk contains the word 'SEQ'.
    #regex match, so it'll match this text anywhere. 
    #maybe need to tighen up to ^SEQ= or similar? 
    if ( m/SEQ/ ) { 
        #choose output filehandle
        $seq_count++;
        select $has_seq;
    }
    else { 
       $no_seq_count++;
       select $no_seq;
    }
    #print current block to selected filehandle. 
    print;
}

select \*STDOUT; 
print "SEQ: $seq_count\n"; 
print "No SEQ: $no_seq_count\n";

这将创建两个文件(创造性地称为“SEQ”和“NO\ SEQ”),并从源代码中分割结果。你知道吗

相关问题 更多 >