Используя perl, как мне найти в текстовом файле _NN (в конце слова) и напечатать слово впереди? - PullRequest
0 голосов
/ 05 мая 2011

Это дает целую строку:

#!/usr/bin/perl

$file = 'output.txt';
open(txt, $file);
while($line = <txt>) {
  print "$line" if $line =~ /_NN/;
}
close(txt);

Ответы [ 4 ]

2 голосов
/ 05 мая 2011
#!/usr/bin/perl
use strict;
use warnings FATAL => "all";
binmode(STDOUT, ":utf8") || die;

my $file = "output.txt";
open(TEXT, "< :utf8", $file)  || die "Can't open $file: $!";
while(<TEXT>) {
    print "$1\n" while /(\w+)_NN\b/g;
}
close(TEXT)                  || die "Can't close $file: $!";
1 голос
/ 10 мая 2011

Ваш сценарий ответа читается немного неловко и содержит несколько потенциальных ошибок. Я бы переписал основной логический цикл так:

foreach my $line (grep { /expend_VB/ } @sentences) {
   my @nouns = grep { /_NN/ } split /\s+/, $line; 
   foreach my $word (@nouns) {
      $word =~ s/_NN//;
      print "$word\n";
   }
   print "$line\n" if scalar(@nouns);
}

Вам необходимо поместить объявление my в цикл - в противном случае оно будет сохраняться дольше, чем вы хотите, и, вероятно, может вызвать проблемы позже.

foreach - более распространенная идиома perl для перебора списка.

1 голос
/ 05 мая 2011
print "$1" if $line =~ /(\S+)_NN/;
0 голосов
/ 09 мая 2011
#!/usr/bin/perl
use strict;
use warnings FATAL => "all";
my $search_key = "expend";       ## CHANGE "..." to <>

open(my $tag_corpus, '<', "ch13tagged.txt") or die $!;

my @sentences = <$tag_corpus>; # This breaks up each line into list
my @words;

for (my $i=0; $i <= @sentences; $i++) {
    if ( defined( $sentences[$i] ) and $sentences[$i] =~ /($search_key)_VB.*/i) {
        @words = split /\s/,$sentences[$i]; ## \s is a whitespace

        for (my $j=0; $j <= @words; $j++) {  
#FILTER if word is noun:            
            if ( defined( $words[$j] ) and $words[$j] =~ /_NN/) {


#PRINT word and sentence:
                print "**",split(/_\S+/,$words[$j]),"**", "\n";
                print split(/_\S+/,$sentences[$i]), "\n"

            }
        } ## put print sentences here to print each sentence after all the nouns inside
    }
}

close $tag_corpus     || die "Can't close $tag_corpus: $!";
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...