2011-05-05 31 views
0

这使得整条生产线:使用perl,如何搜索_NN的文本文件(在单词的结尾处)并在前面打印单词?

#!/usr/bin/perl 

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

你需要更具体的获得工作正则表达式。 “单词”由哪些字符组成?是'“w-12#”或'“q:w”'是一个有效的单词吗?附近是否会有其他不相关的字符,如“123_BB,word_NN”?总之,要具体说明你想要的单词,以及它所处的上下文。 – TLP 2011-05-05 20:40:39

回答

1

你的答案脚本读取有点笨拙,并且有几个潜在的错误。我已经重写了主逻辑循环,像这样:

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); 
} 

你需要把内循环声明 - 否则它会持续的时间比你想让它,后来可以想象会出现问题。

foreach是一个更常见的perl习惯用于迭代列表。

1
print "$1" if $line =~ /(\S+)_NN/; 
+1

谢谢你,我会看看我能否继续这样做! – Jon 2011-05-05 20:23:57

2
#!/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

感谢!我以后可能需要帮助,因为这只是一个开始,但你让我有一个好的开始! – Jon 2011-05-05 20:21:49

-1
#!/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: $!"; 
+2

欢迎来到计算器。我不太确定这里的答案是什么,它非常简洁。如果这是你现有的解决方案/起点,那么它将更适合作为对原始问题的编辑,而不是自己的答案。如果这是一个答案,这将是值得详细说明,以便其他人通过谷歌后来找到它可以看到它更清楚地回答你的问题。 – Flexo 2011-05-09 22:11:34

相关问题