【问题标题】:perl Script to search for a motif in a multifasta file and print the complete sequence along with the header lineperl 脚本在 multifasta 文件中搜索主题并打印完整序列以及标题行
【发布时间】:2016-04-02 00:26:27
【问题描述】:

我能够在多 fasta 文件中搜索主题并打印包含主题的行....但我需要打印所有序列以及包含 fasta 序列的主题的标题行。请帮助我,我只是 perl 的初学者

#!usr/bin/perl -w
use strict;

print STDOUT "Enter the motif: ";
my $motif = <STDIN>;
chomp $motif;


my $line;
open (FILE, "data.fa");
while ($line = <FILE>) {
  if ($line =~ /$motif/)  {
     print $line;
   }
}

【问题讨论】:

    标签: perl bioinformatics


    【解决方案1】:

    试试这个:

    Bio::DB::Fasta

    页面上的说明。如需更多示例或说明,只需在 Google 上搜索:“使用 Bio::DB::Fasta”

    要安装它,只需按照以下任何说明进行操作,我建议以超级用户身份使用 CPAN.pm 方法:

    Installing Perl Modules

    【讨论】:

    • 非常感谢您的回复.....因为我还是 perl 的初学者,所以我需要一个纯 perl 脚本而不是 bioperl 模块。
    • 既然是初学者,为什么需要纯 Perl?
    • 对于初学者来说,从小型、自包含的程序中学习比大型 API 更容易。尤其是在这种情况下 - 学习解析 FASTA 文件是使用脚本进行简单解析的一个很好的介绍。
    【解决方案2】:

    您上面编写的脚本不记得当前的序列标识符,因此您不知道哪个标识符与每个序列相关联。

    我在下面修改了您的脚本,将所有 FASTA 序列读入映射(标识符 => 序列)的散列,然后迭代该散列,在适当的时候打印出匹配项。对于非常大的序列文件,这将是一种不合适的方法,但是在编写新脚本来分析数据时,学习如何编写这样的小辅助函数可能会大大加快速度。了解如何在 Perl 中使用和操作哈希和其他数据结构也很重要,因为您遇到的大多数代码都不是初学者编写的。

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    print STDOUT "Enter the motif: ";
    my $motif = <STDIN>;
    chomp $motif;
    
    my %seqs = %{ read_fasta_as_hash( 'data.fa' ) };
    foreach my $id ( keys %seqs ) {
        if ( $seqs{$id} =~ /$motif/ ) {
            print $id, "\n";
            print $seqs{$id}, "\n";
        }
    }
    
    sub read_fasta_as_hash {
        my $fn = shift;
    
        my $current_id = '';
        my %seqs;
        open FILE, "<$fn" or die $!;
        while ( my $line = <FILE> ) {
            chomp $line;
            if ( $line =~ /^(>.*)$/ ) {
                $current_id  = $1;
            } elsif ( $line !~ /^\s*$/ ) { # skip blank lines
                $seqs{$current_id} .= $line
            }
        }
        close FILE or die $!;
    
        return \%seqs;
    }
    

    【讨论】:

      【解决方案3】:

      @james_thompson 的回答很棒。如果您正在寻找更多功能的东西,我会使用它。如果您正在寻找一个更简单的版本(也许用于教学?),这也足够了 - 但请注意,如果中间有一个艰难的回报,这将错过主题。

      #!usr/bin/perl -w
      use strict;
      
      print STDOUT "Enter the motif: ";
      my $motif = <STDIN>;
      chomp $motif;
      
      
      my $line;
      my $defline;
      open (FILE, "data.fa");
      while ($line = <FILE>) {
        if ($line =~ /^>/) {
           $defline = $line;
         } elsif ($line =~ /$motif/)  {
           print($defline,$line);
         }
      }
      close (FILE);
      

      您会注意到我还在文件句柄上添加了显式关闭。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-07-08
        • 1970-01-01
        • 2011-06-14
        • 1970-01-01
        • 2016-04-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多