2012-05-07 27 views
1

我用下面的例子Lingua::StopWords我怎样才能得到这个打印到我的文件,而不是我的Perl程序中的屏幕?

use Lingua::StopWords qw(getStopWords); 
my $stopwords = getStopWords('en'); 

my @words = qw(i am the walrus goo goo g'joob); 

# prints "walrus goo goo g'joob" 
print join ' ', grep { !$stopwords->{$_} } @words; 

我如何得到它使用我$document,删除停用词并打印结果到一个文件?看到我的代码在这里:

open(FILESOURCE, "sample.txt") or die("Unable to open requested file."); 
my $document = <FILESOURCE>; 
close (FILESOURCE); 

open(TEST, "results_stopwords.txt") or die("Unable to open requested file."); 

use Lingua::StopWords qw(getStopWords); 
my $stopwords = getStopWords('en'); 

print join ' ', grep { !$stopwords->{$_} } $document; 

我想这些变化:

print join ' ', grep { !$stopwords->{$_} } TEST; 


print TEST join ' ', grep { !$stopwords->{$_} } @words; 

基本上,我怎么一个文件中读取,删除停用词,然后将结果写入到一个新的文件?

+1

您需要打开文件进行书写。使用警告并检查打印是否成功,并且您将看到(例如,打印...或死亡...)。请请将文件名和$!在你的错误信息中。 –

+4

外壳重定向有什么问题?这是做这些事情的正常方式。在程序中硬编码输入和输出的路径可能没有意义。这就是stdin(或ARGV)和stdout的用途。 – tchrist

+0

不要忘记关闭文件并检查它是否成功。 –

回答

3

在您的程序中,您忘记了将输入文本标记为单词。 Lingua::EN::Splitter::words的简单替代方法是将split空格上的一行代码转换为单词列表(近似)。

考虑到tchrist的评论,该程序适合用作Unix过滤器。

use strictures; 
use Lingua::StopWords qw(getStopWords); 
use Lingua::EN::Splitter qw(words); 
my $stopwords = getStopWords('en'); 
while (defined(my $line = <>)) { 
    print join ' ', grep { !$stopwords->{$_} } @{ words $line }; 
} 
+0

+1,但不需要'while'中定义的检查。 –

+2

我们的编辑重叠。让我们更好地保持这种方式,编译器优化是最新的,不包括更复杂的表达式;我想要的代码对于复制粘贴编程是强大的。 – daxim

相关问题