【问题标题】:Perl: append numbers from one file to strings of second filePerl:将数字从一个文件附加到第二个文件的字符串
【发布时间】:2015-03-07 18:47:39
【问题描述】:

我想将附加到一个文件中(Unicode)字符串的数字附加到第二个文件中的匹配字符串。不知何故,我无法理解如何做到这一点。这是我的两个文件的样子。

文件 1:

दौरा, 2
प्रोत्साहन, 1
प्रगति, 4

文件 2:

दौरा
dorA

प्रोत्साहन
prua2ts3Ahan
prua2ts2Ahan
prua2tsAhan
prua2t2s3Ahan
prua2t2s2Ahan
prua2t2sAhan
prOts3Ahan
prOts2Ahan
prOtsAhan
prOt2s3Ahan
prOt2s2Ahan
prOt2sAhan

प्रगति
praGat2I
praGatI
pragat2I
pragatI

想要的结果如下所示:

输出:

dorA, 2

prua2ts3Ahan, 1
prua2ts2Ahan, 1
prua2tsAhan, 1
prua2t2s3Ahan, 1
prua2t2s2Ahan, 1
prua2t2sAhan, 1
prOts3Ahan, 1
prOts2Ahan, 1
prOtsAhan, 1
prOt2s3Ahan, 1
prOt2s2Ahan, 1
prOt2sAhan, 1

praGat2I, 4
praGatI, 4
pragat2I, 4
pragatI, 4

我有一个从文件 1 创建的散列,其中字符串作为键,数字作为值。现在需要匹配文件 2 中的这些键,在匹配后收集所有后续行,并将值附加到以下行。有人能指出我正确的方向吗?

【问题讨论】:

    标签: string perl unicode pattern-matching


    【解决方案1】:

    您对解决方案的描述是正确的。现在只需将其转换为代码:

    #!/usr/bin/perl
    use warnings;
    use strict;
    
    my %hash;
    
    open my $F1, '<:encoding(UTF-8)', 'file.1' or die $!;
    while (<$F1>) {
        chomp;
        my ($word, $num) = split /, /;
        $hash{$word} = $num;
    }
    
    open my $F2, '<:encoding(UTF-8)', 'file.2' or die $!;
    my $word;
    while (<$F2>) {
        chomp;
        if (exists $hash{$_}) {
            $word = $_;
        } elsif ($_) {
            print "$_, $hash{$word}\n";
        } else {
            print "\n";
        }
    }
    

    【讨论】:

    • 谢谢 - 非常简单的解决方案。 elsif 声明是我缺少的声明。这基本上从if 语句中的哈希调用中记住$word - 对吗?我一直在摸索$nextline = &lt;&gt; 等等以继续下一行,但我现在意识到这甚至没有必要。还有一个问题:输出文件的第一行不包含任何前导空格,但所有其他行都包含一个前导空格。怎么会?
    • @SebastianSulger:是的,正确。空格可能来自输入文件 - 我的输出与您提供的相同。
    猜你喜欢
    • 2015-12-29
    • 2021-09-04
    • 1970-01-01
    • 2013-04-10
    • 1970-01-01
    • 2014-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多