从 perl 文本文件中搜索以 'ing' 结尾的单词 [英] Search for words ending with 'ing' from a text file in perl
问题描述
我有一个文本文件,我们称之为 file1.txt :
I have a text file , lets call it file1.txt :
cats
and
dogs
are
running
around
|
john
loves
mary
|
I
am
swimming
|
我正在尝试构建一个程序,该程序查找以 'ing' 结尾的单词,并在同一个文件或不同的 output.txt 文件中将它们旁边的 CC 打印出来.
I am trying to build a program which looks for the words ending with 'ing' and prints CC beside them on the same file or to a different output.txt file.
期望输出
cats
and
dogs
are
running CC
around
|
john
loves
mary
|
I
am
swimming CC
|
我浏览了论坛中的可用文章并尝试构建以下代码,但是它给了我任意结果,每个单词后跟CC".
I went through the available articles in the forum and tried building the following code ,however it gives me an arbitrary result with every word followed by " CC ".
use warnings;
use strict;
my $file = 'file1.txt';
open(my $word_fh,"file1.txt") or die "Couldn't open file file1.txt, $!";
my %word_match = map {chomp $_; $_ => 0} <$word_fh>;
close $word_fh;
open my $fh, '<', $file or die $!;
while (<$fh>){
chomp;
my @words_in_line = split;
for my $word (@words_in_line){
$word =~ /ing$/;
$word .= ' CC' if exists $word_match{$word};
print " $word\n";
}
}
我得到的输出是这样的:
The output that I get is this :
cats CC
and CC
dogs CC
are CC
running CC
around CC
| CC
john CC
loves CC
mary CC
| CC
I CC
am CC
swimming
| CC
我知道我做错了什么.任何提示或建议将不胜感激.提前致谢!
I know I am doing something wrong. Any hints or suggestions would be appreciated. Thanks in advance !
推荐答案
那是因为您正在阅读 file1.txt 两次并检查它们是否匹配.在while
循环中,如果file1.txt 的当前行也包含在file1.txt 中的某处,则打印CC".由于它们是相同的文件,因此总是如此,并且在每一行之后打印CC".
That's because you are reading your file1.txt twice and check whether they match. In the while
loop you print 'CC' if the current line of file1.txt is also contained somewhere in file1.txt. Since they are the same files this is always true and 'CC' is printed after every line.
您可能受到了这个问题的启发,其中 OP 想要检查文件 A 中的单词是否也包含在文件 B.您的情况不同,因为您没有两个文件.
You might have been inspired by this question where the OP wanted to check whether words in file A are also contained in file B. Yours is a different case because you don't have two files.
将 file1.txt 的第一次读取放入 %word_match
并只迭代一次文件.您的行 $word =~/ing$/;
仅检查 $word
是否以 ing
结尾,但将结果丢弃.这就像写作
Drop the first reading of file1.txt into %word_match
and iterate over the file just once. Your line $word =~ /ing$/;
only checks whether $word
ends in ing
but throws the result away. That is like writing
$i > 5;
print "i is greater than 5\n";
你必须把它改成
if ( $i > 5 ) {
print "i is greater than 5\n";
}
总而言之,这给出了
#!/usr/bin/env perl
use strict;
use warnings;
open my $fh, '<', 'file1.txt' or die $!;
while ( <$fh> ){
chomp;
print $_;
if ( /ing\s*$/ ) {
print ' CC';
}
print "\n";
}
close($fh);
这篇关于从 perl 文本文件中搜索以 'ing' 结尾的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!