gpt4 book ai didi

arrays - Perl - 在关联数组单词和单词上下文中查找并保存

转载 作者:行者123 更新时间:2023-12-01 16:28:08 26 4
gpt4 key购买 nike

我有一个像这样的数组(这只是一个小概述,但它有 2000 行甚至更多这样的行):

@list = (
"affaire,chose,question",
"cause,chose,matière",
);

我想要这样的输出:

%te = (
affaire => "chose", "question",
chose => "affaire", "question", "cause", "matière",
question => "affaire", "chose",
cause => "chose", "matière",
matière => "cause", "chose"
);

我已经创建了这个脚本,但它运行得不太好,而且我认为太复杂了..

use Data::Dumper;
@list = (
"affaire,chose,question",
"cause,chose,matière",
);

%te;

for ($a = 0; $a < @list; $a++){
@split_list = split (/,/,$list[$a]);
}

foreach $elt (@split_list){
print "SPLIT ELT : $split_list[$elt]\n";

for ($i = 0; $i < @list; $i++){

$test = $list[$i]; #$test = "affaire,chose,question"

if (exists $te{$split_list[$elt]}){ #if exists affaire in %te

@t = split (/,/,$test); # @t = affaire chose question
print "T : @t\n";

@temp = grep(!/$split_list[$elt]/, @t);
print "GREP : @temp\n";#@temp = chose question

@fin = join(', ', @temp); #@fin = chose, question;

for ($k = 0; $k < @fin; $k++){
$te{$split_list[$elt]} .= $fin[$k]; #affaire => chose, question
}

}
else {

@t = split (/,/,$test); # @t = affaire chose question
print "T : @t\n";

@temp = grep(!/$split_list[$elt]/, @t);
print "GREP : @temp\n";#@temp = chose question

@fin = join(', ', @temp); #@fin = chose, question;

for ($k = 0; $k < @fin; $k++){
$te{$split_list[$elt]} = $fin[$k];
}
}
}

}



print Dumper \%te;

输出:

SPLIT ELT : cause
T : affaire chose question
GREP : affaire chose question
T : cause chose matière
GREP : chose matière
SPLIT ELT : cause
T : affaire chose question
GREP : affaire chose question
T : cause chose matière
GREP : chose matière
SPLIT ELT : cause
T : affaire chose question
GREP : affaire chose question
T : cause chose matière
GREP : chose matière
$VAR1 = {
'cause' => 'affaire, chose, questionchose, matièreaffaire, chose, questionchose, matièreaffaire, chose, questionchose, matière'
};

最佳答案

对于@list中的每个元素,在,处进行拆分,并将每个字段作为%te的key,将其他元素推送到该键的值:

#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;

my @list = (
"affaire,chose,question",
"cause,chose,matière",
);

my %te;

foreach my $str (@list) {
my @field = split /,/, $str;
foreach my $key (@field) {
my @other = grep { $_ ne $key } @field;
push @{$te{$key}}, @other;
}
}

print Dumper(\%te);
<小时/>

输出:

$ perl t.pl
$VAR1 = {
'question' => [
'affaire',
'chose'
],
'affaire' => [
'chose',
'question'
],
'matière' => [
'cause',
'chose'
],
'cause' => [
'chose',
'matière'
],
'chose' => [
'affaire',
'question',
'cause',
'matière'
]
};

关于arrays - Perl - 在关联数组单词和单词上下文中查找并保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23780320/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com