gpt4 book ai didi

perl - 在 Perl 中逐字而不是逐行读取文本文件

转载 作者:行者123 更新时间:2023-12-02 20:27:46 25 4
gpt4 key购买 nike

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

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

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

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

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

最佳答案

不要一口气读完它,而是尝试逐行的方法,这种方法也更容易减少计算机的内存使用(尽管 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);

关于perl - 在 Perl 中逐字而不是逐行读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18668853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com