gpt4 book ai didi

perl - 如何在Perl中匹配两个文档之间的字符串顺序?

转载 作者:行者123 更新时间:2023-12-04 18:36:22 25 4
gpt4 key购买 nike

我在制作一个PERL程序以匹配两个文档中的单词时遇到问题。假设有文件A和B。

所以我想删除文档A中不在文档B中的单词。

范例1:

我吃披萨

B:她去市场吃披萨

结果:吃披萨

范例2:
A:吃披萨

B:披萨吃

结果:披萨
(单词order是相关的,因此“ eat”被删除。)

我在系统上使用Perl,每个文档中的句子不是很多,所以我认为我不会使用SQL

该程序是印度尼西亚语言(Bahasa)自动论文评分的子程序

谢谢
抱歉,我的问题有点令人困惑。我真的对“这个世界”陌生:)

最佳答案

好的,我目前无法访问,因此不能保证100%甚至无法编译,但应提供足够的指导:

解决方案1 ​​:(单词顺序无关紧要)

#!/usr/bin/perl -w

use strict;
use File::Slurp;

my @B_lines = File::Slurp::read_file("B") || die "Error reading B: $!";
my %B_words = ();
foreach my $line (@B_lines) {
map { $B_words{$_} = 1 } split(/\s+/, $line);
}
my @A_lines = File::Slurp::read_file("A") || die "Error reading A: $!";
my @new_lines = ();
foreach my $line (@A_lines) {
my @B_words_only = grep { $B_words{$_} } split(/\s+/, $line);
push @new_lines, join(" ", @B_words_only) . "\n";
}
File::Slurp::write_file("A_new", @new_lines) || die "Error writing A_new: $!";


这将创建一个新文件“ A_new”,其中仅包含A在B中的单词。

这有一个小错误-它将用单个空格替换文件A中的任何多个空格,因此

    word1        word2              word3


会变成

word1 word2 word3


它可以固定,但是这样做确实很烦人,所以除非您绝对要求正确保留100%空格,否则我不会打扰。

解决方案2 :(单词顺序很重要,但是您可以从文件A中打印单词,而无需考虑保留空格)

#!/usr/bin/perl -w

use strict;
use File::Slurp;

my @A_words = split(/\s+/gs, File::Slurp::read_file("A") || die "Error reading A:$!");
my @B_words = split(/\s+/gs, File::Slurp::read_file("B") || die "Error reading B:$!");
my $B_counter = 0;
for (my $A_counter = 0; $A_counter < scalar(@A_words); ++$A_counter) {
while ($B_counter < scalar(@B_words)
&& $B_words[$B_counter] ne $A_words[$A_counter]) {++$B_counter;}
last if $B_counter == scalar(@B_words);
print "$A_words[$A_counter]";
}


解决方案3(为什么我们再次需要Perl?:))

您可以在没有Perl的外壳中轻松完成此操作(或通过系统()调用或父Perl脚本中的反引号)

comm -12 A B | tr "\012" " " 


要从Perl调用它:

my $new_text = `comm -12 A B | tr "\012" " " `;


但是,请看我的最后评论,至少在循环访问大量文件并关心性能的情况下,至少可以将其视为“错误的Perl” ...

关于perl - 如何在Perl中匹配两个文档之间的字符串顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2894213/

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