這使得整條生產線:使用perl,如何搜索_NN的文本文件(在單詞的結尾處)並在前面打印單詞?
#!/usr/bin/perl
$file = 'output.txt';
open(txt, $file);
while($line = <txt>) {
print "$line" if $line =~ /_NN/;
}
close(txt);
這使得整條生產線:使用perl,如何搜索_NN的文本文件(在單詞的結尾處)並在前面打印單詞?
#!/usr/bin/perl
$file = 'output.txt';
open(txt, $file);
while($line = <txt>) {
print "$line" if $line =~ /_NN/;
}
close(txt);
你的答案腳本讀取有點笨拙,並且有幾個潛在的錯誤。我已經重寫了主邏輯循環,像這樣:
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習慣用於迭代列表。
#!/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: $!";
感謝!我以後可能需要幫助,因爲這只是一個開始,但你讓我有一個好的開始! – Jon 2011-05-05 20:21:49
#!/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: $!";
歡迎來到計算器。我不太確定這裏的答案是什麼,它非常簡潔。如果這是你現有的解決方案/起點,那麼它將更適合作爲對原始問題的編輯,而不是自己的答案。如果這是一個答案,這將是值得詳細說明,以便其他人通過谷歌後來找到它可以看到它更清楚地回答你的問題。 – Flexo 2011-05-09 22:11:34
你需要更具體的獲得工作正則表達式。 「單詞」由哪些字符組成?是'「w-12#」或'「q:w」'是一個有效的單詞嗎?附近是否會有其他不相關的字符,如「123_BB,word_NN」?總之,要具體說明你想要的單詞,以及它所處的上下文。 – TLP 2011-05-05 20:40:39