6

我有一个大 (300 kB) 文本文件,其中包含由空格分隔的单词。现在我想打开这个文件并一个一个地处理其中的每个单词。

问题是 perl 逐行读取文件(即)一次读取整个文件,这给了我奇怪的结果。我知道正常的方法是做类似的事情

open($inFile, 'tagged.txt') or die $!;
$_ = <$inFile>;
@splitted = split(' ',$_);
print $#splitted;

但这给了我一个错误的字数(数组太大?)。

是否可以逐字读取文本文件?

4

4 回答 4

5

与其一口气读完,不如试试逐行的方法,这对你的机器的内存使用也更容易(尽管 300 KB 对于现代计算机来说并不算大)。

use strict;
use warnings;

my @words;
open (my $inFile, '<', 'tagged.txt') or die $!;

while (<$inFile>) {
  chomp;
  @words = split(' ');
  foreach my $word (@words) { # process }
}

close ($inFile);
于 2013-09-07T02:23:24.250 回答
4

要一次读取一个单词,请将输入记录分隔符 ( $/) 更改为空格:

local $/ = ' ';

例子:

#!/usr/bin/perl
use strict;
use warnings;

use feature 'say';

{
    local $/ = ' ';

    while (<DATA>) {
        say;
    }
}

__DATA__
one two three four five

输出:

one 
two 
three 
four 
five
于 2013-09-07T08:28:43.740 回答
2

目前尚不清楚您输入的文件是什么样的,但您暗示它只包含由许多“单词”组成的一行。

300KB 远非“大文本文件”。你应该完整地阅读它,并从那里一个接一个地提取单词。这个程序演示

use strict;
use warnings;

my $data = do {
  open my $fh, '<', 'data.txt' or die $!;
  local $/;
  <$fh>;
};

my $count = 0;
while ($data =~ /(\S+)/g ) {
  my $word = $1;
  ++$count;
  printf "%2d: %s\n", $count, $word;
}

输出

 1: alpha
 2: beta
 3: gamma
 4: delta
 5: epsilon

如果没有更多解释“错误字数”可能是什么,很难提供帮助,但可以肯定的是问题不是因为数组的大小:如果那里有问题,那么 Perl 会引发异常然后死。

但是,如果您将结果与文字处理器的统计数据进行比较,那么可能是因为“单词”的定义不同。例如,文字处理器可以将连字符的单词视为两个单词。

于 2013-09-07T14:19:13.937 回答
1

300K好像不大,可以试试:

my $text=`cat t.txt` or die $!;
my @words = split /\s+/, $text;
foreach my $word (@words) { # process }

或稍微修改过的 squiguy 解决方案

use strict;
use warnings;

my @words;
open (my $inFile, '<', 'tagged.txt') or die $!;

while (<$inFile>) {
  push(@words,split /\s+/);
}
close ($inFile);
foreach my $word (@words) { # process }
于 2013-09-07T19:20:40.227 回答