从文件中提取特定数据并将其写入另一个文件

时间:2013-01-11 20:55:32

标签: python perl biopython

我在这里标记了python和perl只是因为这是我迄今为止所使用的内容。如果有人知道更好的方法,我当然愿意尝试一下。无论如何,我的问题:

我需要为基因预测程序创建一个输入文件,其格式如下:

seq1 5 15
seq1 20 34

seq2 50 48
seq2 45 36

seq3 17 20

其中seq#是geneID,右边的数字是开放阅读框内外显子的位置。现在我在.gff3文件中有这些信息,其中包含很多其他信息。我可以使用excel打开它,并轻松删除包含不相关数据的列。以下是它的安排:

PITG_00002  .   gene    2   397 .   +   .   ID=g.1;Name=ORF%
PITG_00002  .   mRNA    2   397 .   +   .   ID=m.1;
**PITG_00002**  .   exon    **2 397**   .   +   .   ID=m.1.exon1;
PITG_00002  .   CDS 2   397 .   +   .   ID=cds.m.1;

PITG_00004  .   gene    1   1275    .   +   .   ID=g.3;Name=ORF%20g
PITG_00004  .   mRNA    1   1275    .   +   .   ID=m.3;
**PITG_00004**  .   exon    **1 1275**  .   +   .   ID=m.3.exon1;P
PITG_00004  .   CDS 1   1275    .   +   .   ID=cds.m.3;P

PITG_00004  .   gene    1397    1969    .   +   .   ID=g.4;Name=
PITG_00004  .   mRNA    1397    1969    .   +   .   ID=m.4;
**PITG_00004**  .   exon    **1397  1969**  .   +   .   ID=m.4.exon1;
PITG_00004  .   CDS 1397    1969    .   +   .   ID=cds.m.4;

所以我只需要粗体数据。例如,

PITG_0002 2 397

PITG_00004 1 1275
PITG_00004 1397 1969

非常感谢您给予的任何帮助,谢谢!

编辑:嗯,我搞砸了格式化。 **之间的任何东西都是我需要的东西。

4 个答案:

答案 0 :(得分:2)

在Unix中:

grep <file.gff3 " exon " |
    sed "s/^\([^ ]+\) +[.] +exon +\([0-9]+\) \([0-9]+\).*$/\1 \2 \3/"

答案 1 :(得分:1)

对于行人:

(这是Python)

with open(data_file) as f:
    for line in f:
        tokens = line.split()
        if len(tokens) > 3 and tokens[2] == 'exon':
            print tokens[0], tokens[3], tokens[4]

打印

PITG_00002 2 397
PITG_00004 1 1275
PITG_00004 1397 1969

答案 2 :(得分:1)

看起来您的数据是以制表符分隔的。

此Perl程序将从第三列中exon的所有记录中打印第1,4和5列。您需要将open语句中的文件名更改为实际文件名。

use strict;
use warnings;

open my $fh, '<', 'genes.gff3' or die $!;

while (<$fh>) {
  chomp;
  my @fields = split /\t/;
  next unless @fields >= 5 and $fields[2] eq 'exon';
  print join("\t", @fields[0,3,4]), "\n";
}

<强>输出

PITG_00002  2 397
PITG_00004  1 1275
PITG_00004  1397  1969

答案 3 :(得分:0)

这是一个Perl脚本选项perl scriptName.pl file.gff3

use strict;
use warnings;

while (<>) {
    print "@{ [ (split)[ 0, 3, 4 ] ] }\n" if /exon/;
}

输出:

PITG_00002 2 397
PITG_00004 1 1275
PITG_00004 1397 1969

或者您可以执行以下操作:

perl -n -e 'print "@{ [ (split)[ 0, 3, 4 ] ] }\n" if /exon/' file.gff3

将数据保存到文件中:

use strict;
use warnings;

open my $inFH,  '<',  'file.gff3' or die $!;
open my $outFH, '>>', 'data.txt'  or die $!;

while (<$inFH>) {
    print $outFH "@{ [ (split)[ 0, 3, 4 ] ] }\n" if /exon/;
}
相关问题