-2
我想從文件中讀取並打印出每行上重複單詞的位置。我將每行都存儲在數組中,但我不確定是否這是正確的開始。使用Perl計算和打印重複單詞在一行中的位置
while (my $fileLine = <$fh>){
my @lineWords = split /\s+/, $fileLine;
print "@\n"
}
我想從文件中讀取並打印出每行上重複單詞的位置。我將每行都存儲在數組中,但我不確定是否這是正確的開始。使用Perl計算和打印重複單詞在一行中的位置
while (my $fileLine = <$fh>){
my @lineWords = split /\s+/, $fileLine;
print "@\n"
}
#!/usr/bin/perl
use strict;
use warnings;
while (<DATA>){
chomp; # remove end of line chars
my @wordsInLine = split /\s+/, $_;
@wordsInLine = map {lc($_)} @wordsInLine; # convert words to lowercase
my($word, %wordsInLine, $n);
for $word (@wordsInLine) {
$wordsInLine{$word}++; # use hash %wordsInLine to count occurences of words
}
for $word (@wordsInLine) {
$n++;
if((my $count = $wordsInLine{$word}||0) > 1) {
print "line $.: Word $n \"$word\" is repeated $count times\n";
delete($wordsInLine{$word}); # do not generate more than one report
# about the same word in single line
}
}
}
__DATA__
This this is a sample sentence
A that That THAT !
這或許應該被拆分''「','不分裂/ \ s + /'。 – melpomene
我不知道Perl的語法,但是這個想法是:如果你找到一個當前的單詞,第一個單詞增加一個計數器,那麼取出該行的第一個單詞並循環遍歷該行的其餘部分,等等。同樣的第二個字...希望可以幫助:) – Maraboc
@Maraboc根據如何定義「單詞」,「重複」和「位置」,這也可以通過正則表達式來實現。 – melpomene