首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Perl中以反向顺序匹配字符串

在Perl中以反向顺序匹配字符串
EN

Stack Overflow用户
提问于 2015-12-09 19:24:33
回答 2查看 377关注 0票数 2

我在第一列中有两个字符串对,在第一列中用空格分隔,还有两个列有值。我想要创建一个新的文件,在这个文件中,字符串对在同一行中匹配,而不管它们的顺序如何。例如,打印包含对"GAT_1 GAT_2“的行和它旁边包含"GAT_2 GAT_1”的行。在将每个字符串赋值给给定对的变量之后,如何不重复地比较不同行的字符串呢?

代码语言:javascript
复制
# discard headers

foreach $line (@file) {
  @columns = split (/\t/, $line);
  @strings = split (/\s/, $columns[0]);
    # pseudocode:
foreach line that has pair "$strings[0] $strings[1]" {
    print $line,"\t", and $line where pair is "$strings[1] $strings[0]"

Input:
   pair         val1    val2
GAT_1 GAT_2     0.2     4.5
GAT_1 GAT_3     0.1     0.2
GAT_4 GAT_5     0.9     7.5
GAT_5 GAT_4     0.5     8.3
BLAC BABA       8.3     1.3
BABA BLAC       8.9     1.1
GAT_2 GAT_1     1.2     2.1
GAT_3 GAT_1     3.4     4.3


Ouput:
   pair        val1     val2       pair        val1   val2
GAT_1 GAT_2     0.2     4.5    GAT_2 GAT_1     1.2     2.1
GAT_1 GAT_3     0.1     0.2    GAT_3 GAT_1     3.4     4.3
GAT_4 GAT_5     0.9     7.5    GAT_5 GAT_4     0.5     8.3
BLAC BABA       8.3     1.3    BABA BLAC       8.9     1.1
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-12-09 21:31:30

这里有一种解决这个问题的方法,它适用于任意数量的值列。基本的方法是我在comment中建议的方法,即将键规范化,然后将我们找到的任何值推送到数组中。

代码语言:javascript
复制
use strict;
use warnings;

my %unique;

while (<DATA>) {
    chomp;
    next unless /^\S/;
    my @fields = split;

    my $key = join(' ', sort(splice(@fields, 0, 2)));
    push(@{$unique{$key}}, @fields);
}

for my $key (keys(%unique)) {
    print join("\t", $key, @{$unique{$key}});
    print "\n";
}

__DATA__
   pair         val1    val2
GAT_1 GAT_2     0.2     4.5
GAT_1 GAT_3     0.1     0.2
GAT_4 GAT_5     0.9     7.5
GAT_5 GAT_4     0.5     8.3
BLAC BABA       8.3     1.3
BABA BLAC       8.9     1.1
GAT_2 GAT_1     1.2     2.1
GAT_3 GAT_1     3.4     4.3

输出:

代码语言:javascript
复制
GAT_4 GAT_5     0.9     7.5     0.5     8.3
GAT_1 GAT_2     0.2     4.5     1.2     2.1
BABA BLAC       8.3     1.3     8.9     1.1
GAT_1 GAT_3     0.1     0.2     3.4     4.3
票数 0
EN

Stack Overflow用户

发布于 2015-12-09 21:51:19

https://stackoverflow.com/a/34189380/103780中的小改动将给您想要的东西:(未经测试):my @keys = splice(@fields, 0, 2); my $key = join(' ', @keys); my $skey = join (' ', sort @keys); push(@{$unique{$skey}{$key}}, @fields);

for my $skey (keys(%unique)) { for my $key (keys(%unique{$skey})) { print join("\t", $key, @{$unique{$skey}{$key}}); print "\t"; } print "\n"; }

票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34187313

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档